您的位置:首页 > 其它

LeetCode : Add Binary

2012-12-09 09:25 375 查看
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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int i = a.size();
int j = b.size();
if(i == 0) return b;
if(j == 0) return a;
int carry = 0;
string res;
--j;
--i;
while(i >= 0 && j >= 0){
int temp = a[i] - '0' + b[j] - '0' + carry;
carry = temp / 2;
temp %= 2;
res += (char)(temp + '0');
--i;
--j;
}
while(i >= 0){
int temp = a[i] - '0' + carry;
carry = temp / 2;
temp %= 2;
res += (char)(temp + '0');
--i;
}
while(j >= 0){
int temp = b[j] - '0' + carry;
carry = temp / 2;
temp %= 2;
res += (char)(temp + '0');
--j;
}
if(carry){
res += "1";
}
reverse(res.begin(), res.end());
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: