[LeetCode67] Add Binary

题目:

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

分类:String Math

代码:

 1 class Solution {
 2 public:
 3     string addBinary(string a, string b) {
 4         int carry = 0;
 5         string res = a.size() > b.size() ? a : b;
 6         reverse(a.begin(),a.end());
 7         reverse(b.begin(),b.end());
 8         for(int i = 0; i < max(a.size(),b.size()); ++i)
 9         {
10             int x = i < a.size() ? a[i] - '0' : 0;
11             int y = i < b.size() ? b[i] - '0' : 0;
12             res[i] = (x ^ y) ^ carry + '0';
13             carry = x & y | (carry & (x ^ y));
14         }
15         if(carry)
16             res += "1";
17         reverse(res.begin(),res.end());
18         return res;
19     }
20 };

 

posted @ 2016-08-09 22:30  zhangbaochong  阅读(215)  评论(0)    收藏  举报