Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <algorithm>
- using namespace std;
- string addBinary(string a, string b)
- {
- string c;
- int a_pos=a.length()-1,b_pos=b.length()-1;
- bool carry=0;
- while(a_pos>=0||b_pos>=0)
- {
- cout<<"\na_pos:"<<a_pos<<"b_pos"<<b_pos<<endl;
- char temp;
- if(a_pos<0)
- {
- temp=b[b_pos];
- }
- else if(b_pos<0)
- {
- temp=a[a_pos];
- }
- else
- {
- temp=a[a_pos]+b[b_pos]-'0';
- }
- temp+=carry;
- if(temp>='2')
- {
- carry=1;
- temp-=2;
- }
- else carry=0;
- cout<<"temp:"<<temp<<endl;
- c=temp+c;
- if(a_pos<=0&&b_pos<=0&&carry)
- {
- c="1"+c;
- }
- --a_pos;
- --b_pos;
- cout<<"c:"<<c<<endl;
- }
- return c;
- }
- string addBinary_2(string a, string b) {
- int carry = 0;
- int i = a.length() - 1;
- int j = b.length() - 1;
- string ans;
- while (i >= 0 || j >= 0) {
- int s = (i >= 0 ? a[i--] - '0' : 0) +
- (j >= 0 ? b[j--] - '0' : 0) +
- carry;
- carry = s >> 1;
- ans += '0' + (s & 1);
- }
- if (carry) ans += '1';
- reverse(ans.begin(),ans.end());
- return ans;
- }
- int main()
- {
- cout<<addBinary("11","1")<<endl;
- cout<<addBinary("1010","1011")<<endl;
- cout<<"addBinary_2\n";
- cout<<addBinary_2("11","1")<<endl;
- cout<<addBinary_2("1010","1011")<<endl;
- return 0;
- }
Add Comment
Please, Sign In to add comment