class Solution {
public:
string addBinary(string a, string b) {
int i(a.size() - 1), j(b.size() - 1);
int carry(0);
string res("");
while(i >= 0 && j >= 0){
int num = (a[i] - '0') + (b[j] - '0') + carry;
char c = '0' + num%2;
carry = num/2;
res += c;
--i;
--j;
}
while(i >= 0){
int num = (a[i] - '0') + carry;
char c = '0' + num%2;
carry = num/2;
res += c;
--i;
}
while(j >= 0){
int num = (b[j] - '0') + carry;
char c = '0' + num%2;
carry = num/2;
res += c;
--j;
}
if(carry == 1) res += '1';
reverse(res.begin(), res.end());
return res;
}
};
LeetCode之Add Binary
最新推荐文章于 2018-09-23 20:59:58 发布