4/09/2014

Leetcode -- Add Binary

class Solution {  
 public:  
   string addBinary(string a, string b) {  
     if(a.length() < b.length()) {  
       return addBinary(b, a);  
     }  
     int m = a.length() - 1;  
     int n = b.length() - 1;  
     string result;  
     int carry = 0;  
     for(; n >= 0; n--, m--) {  
       int sum = a[m] - '0' + b[n] - '0' + carry;  
       int res = sum % 2;  
       carry = sum / 2;  
       string temp;  
       temp += (res + '0');  
       result = temp+ result;  
     }  
     for(; m >=0; m--) {  
       int sum = a[m] - '0' + carry;  
       int res = sum % 2;  
       carry = sum / 2;  
       string temp;  
       temp += (res + '0');  
       result = temp+ result;  
     }  
     if(carry) {  
       string temp;  
       temp += (carry + '0');  
       result = temp+ result;  
     }  
     return result;  
   }  
 };  

No comments: