Saturday, September 20, 2014

LeetCode: Add Binary

Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".

   string addBinary(string a, string b) {  
     int n1 = a.size();  
     int n2 = b.size();  
     if (n1 == 0)return b;  
     if (n2==0)return a;  
     string *imd = new string[n1+n2+2];  
     string res = *imd;  
     int i = n1-1, j = n2-1, k = 0;  
     int carry = 0;  
     while(i>=0 && j>=0)  
     {  
       int x = (a[i--]-48);  
       int y = (b[j--]-48);  
       int sum = x ^ y ^ carry;  
       res += sum+48;k+=2;  
       carry = x&&y || y&&carry || carry&&x;  
     }  
     while(i>=0)  
     {  
       k++;  
       int x = (a[i--]-48);  
       int sum = x ^ carry;  
       res += sum+48;  
       carry = x&&carry;  
     }  
     while(j>=0)  
     {  
       k++;  
       int x = (b[j--]-48);  
       int sum = x ^ carry;  
       res += sum+48;  
       carry = x&&carry;  
     }  
     if(carry)  
     {  
       res += carry+48;  
       k++;  
     }  
     int n;  
     i = 0, j = res.length()-1;  
     while(i<j)  
     {  
       swap(res[i],res[j]);  
       i++;  
       j--;  
     }  
     return res;  
   }  

No comments:

Post a Comment