您的位置:首页 > 其它

二进制求和

2017-03-16 19:31 204 查看
给定两个二进制字符串,返回他们的和(用二进制表示)。

样例

a = 
11


b = 
1


返回 
100

解题思路:巧用a[i] - '0'

class Solution {
public:
/**
* @param a a number
* @param b a number
* @return the result
*/
string addBinary(string& a, string& b) {
// Write your code here
string result;
int temp = 0;
auto length = a.size() > b.size() ? a.size() : b.size();
reverse(a.begin(),a.end());
reverse(b.begin(),b.end());
for (auto i = 0; i < length; i++)
{
int aa = i < a.size() ? a[i] - '0' : 0;
int bb = i < b.size() ? b[i] - '0' : 0;
int val = (aa + bb + temp) % 2;
temp = (aa + bb + temp) / 2;
result.insert(result.begin(), val + '0');
}
if (temp == 1)
{
result.insert(result.begin(), 1 + '0');
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: