Add Binary

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

Solution: '1'-'0' = 1.

 1 class Solution {
 2 public:
 3     string addBinary(string a, string b) {
 4         int N = a.size();
 5         int M = b.size();
 6         int K = max(M, N);
 7         string res(K,' ');
 8         int carry = 0;
 9         int i = N - 1, j = M - 1, k = K - 1;
10         while(i >= 0 || j >= 0) {
11             int sum = carry;
12             if(i >= 0) sum += a[i--] - '0';
13             if(j >= 0) sum += b[j--] - '0';
14             carry = sum / 2;
15             res[k--] = sum % 2 + '0'; 
16         }
17         if(carry == 1) res.insert(res.begin(), '1');
18         return res;
19     }
20 };

 

posted @ 2014-04-15 13:16  beehard  阅读(104)  评论(0编辑  收藏  举报