题目描述:
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) {
string ret;
int inc(0);
int LEN = max(a.length(), b.length());
for (int i = 0; i <LEN; i++){
if (a.length() > i)
inc += a[a.length() - i - 1] - '0';
if (b.length() > i)
inc += b[b.length() - i - 1] - '0';
ret = (char)(inc % 2 + '0') + ret;
inc >>= 1;
}
if (inc)
ret = '1' + ret;
return ret;
}
};