您的位置:首页 > 其它

[LeetCode]34. Add Binary二进制相加

2015-10-23 10:09 267 查看
Given two binary strings, return their sum (also a binary string).

For example,
a =
"11"

b =
"1"

Return
"100"
.

解法:从后往前对两个string相加即可。注意将char转换为int,注意进位,注意结果顺序。

class Solution {
public:
string addBinary(string a, string b) {
int as = a.size(), bs = b.size();
if (bs > as) return addBinary(b, a);
int i = as - 1, j = bs - 1, carry = 0;
string res = "";
while (i >= 0)
{
int curr = (int)(a[i] - '0') + carry + (j >= 0 ? (int)(b[j] - '0') : 0);
res += (char)(curr % 2 + '0');
carry = curr / 2;
i--; j--;
}
res = carry == 1 ? res + '1' : res;
reverse(res.begin(), res.end());
return res;
}
};


或者直接使用string的insert成员函数:

class Solution {
public:
string addBinary(string a, string b) {
int as = a.size(), bs = b.size();
if (bs > as) return addBinary(b, a);
int i = as - 1, j = bs - 1, carry = 0;
string res = "";
while (i >= 0)
{
int curr = (int)(a[i] - '0') + carry + (j >= 0 ? (int)(b[j] - '0') : 0);
res.insert(0, 1, (char)(curr % 2 + '0'));
carry = curr / 2;
i--; j--;
}
res = carry == 1 ? res.insert(0, 1, '1') : res;
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: