Saturday, May 9, 2015

Add Binary

来源:Leetcode

原帖:http://oj.leetcode.com/problems/add-binary/

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

代码:
 class Solution {  
 public:  
   string addBinary(string a, string b) {  
     int N = a.size(), M = b.size(), K = max(N, M);  
     string res(K, ' ');  
     int carry = 0;  
     int i = N - 1, j = M - 1, k = K - 1;  
     while (i >= 0 || j >= 0) {  
       int sum = carry;  
       if (i >= 0) sum += a[i--] - '0';  
       if (j >= 0) sum += b[j--] - '0';  
       carry = sum / 2;  
       res[k--] = sum % 2 + '0';  
     }  
     if (carry == 1) {  
       res.insert(res.begin(), '1');  
     }  
     return res;  
   }  
 };  


No comments:

Post a Comment