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) {
if(a.size() == 0) return b;
if(b.size() == 0) return a;
string ret;
int carry = 0;
int i = a.size() - 1;
int j = b.size() - 1;
while(i>=0 && j>=0) {
int tmp = a[i] - '0' + b[j] - '0' + carry;
carry = tmp / 2;
ret = (char)('0' + tmp%2) + ret;
--i;
--j;
}
while(i>=0) {
int tmp = a[i] - '0' + carry;
carry = tmp/2;
ret = (char)('0' + tmp%2) + ret;
--i;
}
while(j>=0) {
int tmp = b[j] - '0' + carry;
carry = tmp/2;
ret = (char)('0' + tmp%2) + ret;
--j;
}
if(carry) ret = (char)('0' + carry) + ret;
return ret;
}
};
欢迎关注微信公众号——计算机视觉: