此题为二进制加法,发放很自然,将两个字符串以尾部对齐,从后往前依次相加,注意进位。
难点在于对字符串的操作,string为C++中的字符串类,添加单个字符或字符串均可直接利用‘+’来进行连接
且注意char转化为int方式,即直接加减 ‘0’ 即可
代码
class Solution {
public:
string addBinary(string a, string b) {
string result;
int alen = a.length();
int blen = b.length();
if(alen==0)
return b;
if(blen==0)
return a;
int i = alen - 1;
int j = blen - 1;
int carry = 0;
while(i>=0&&j>=0)
{
int digit = (a[i]-'0'+b[j]-'0'+carry)%2;
carry = (a[i]-'0'+b[j]-'0'+carry)/2;
result += char(digit + '0');
i--;
j--;
}
while(i>=0)
{
int digit = (a[i]-'0'+ carry)%2;
carry = (a[i]-'0'+ carry)/2;
result += char(digit + '0');
i--;
}
while(j>=0)
{
int digit = (b[j]-'0'+ carry)%2;
carry = (b[j]-'0'+ carry)/2;
result += char(digit + '0');
j--;
}
if(carry>0)
result += char(carry + '0');
reverse(result.begin(), result.end());
return result;
}
};
本文介绍了一种解决二进制加法问题的算法实现,通过字符串操作完成两个二进制数的加法运算,包括处理进位逻辑,并提供了一个完整的C++代码示例。
1922

被折叠的 条评论
为什么被折叠?



