gha890826

LeetCode - 67. Add Binary

May 13th, 2020 (edited)
1,312
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <algorithm>
  4. using namespace std;
  5. string addBinary(string a, string b)
  6. {
  7.     string c;
  8.     int a_pos=a.length()-1,b_pos=b.length()-1;
  9.     bool carry=0;
  10.     while(a_pos>=0||b_pos>=0)
  11.     {
  12.         cout<<"\na_pos:"<<a_pos<<"b_pos"<<b_pos<<endl;
  13.         char temp;
  14.         if(a_pos<0)
  15.         {
  16.             temp=b[b_pos];
  17.         }
  18.         else if(b_pos<0)
  19.         {
  20.             temp=a[a_pos];
  21.         }
  22.         else
  23.         {
  24.             temp=a[a_pos]+b[b_pos]-'0';
  25.         }
  26.         temp+=carry;
  27.         if(temp>='2')
  28.         {
  29.             carry=1;
  30.             temp-=2;
  31.         }
  32.         else carry=0;
  33.         cout<<"temp:"<<temp<<endl;
  34.         c=temp+c;
  35.         if(a_pos<=0&&b_pos<=0&&carry)
  36.         {
  37.             c="1"+c;
  38.         }
  39.         --a_pos;
  40.         --b_pos;
  41.         cout<<"c:"<<c<<endl;
  42.     }
  43.     return c;
  44. }
  45.  
  46. string addBinary_2(string a, string b) {
  47.     int carry = 0;
  48.     int i = a.length() - 1;
  49.     int j = b.length() - 1;
  50.     string ans;
  51.     while (i >= 0 || j >= 0) {
  52.       int s = (i >= 0 ? a[i--] - '0' : 0) +
  53.               (j >= 0 ? b[j--] - '0' : 0) +
  54.               carry;
  55.       carry = s >> 1;
  56.       ans += '0' + (s & 1);
  57.     }
  58.     if (carry) ans += '1';
  59.     reverse(ans.begin(),ans.end());
  60.     return ans;
  61.   }
  62.  
  63. int main()
  64. {
  65.     cout<<addBinary("11","1")<<endl;
  66.     cout<<addBinary("1010","1011")<<endl;
  67.     cout<<"addBinary_2\n";
  68.     cout<<addBinary_2("11","1")<<endl;
  69.     cout<<addBinary_2("1010","1011")<<endl;
  70.     return 0;
  71. }
Add Comment
Please, Sign In to add comment