描述
string类型的二进制数的加法
解决
模拟
class Solution {
public:
string addBinary(string a, string b){
int posA = a.size();
int posB = b.size();
//string res = "";
int minLenth = (posA >= posB) ? posB : posA;
// cout << minLenth << endl;
// minLenth;
int maxLenth = (posA >= posB) ? posA : posB;
// maxLenth;
string res(maxLenth + 1, '0');
int carry = 0;
--posA, --posB;
while (posA >= 0 || posB >= 0 || carry >= 1){
int tmpA = posA >= 0 ? a[posA] - '0' : 0;
int tmpB = posB >= 0 ? b[posB] - '0' : 0;
int tmpSum = tmpA + tmpB + carry;
carry = tmpSum / 2;
// cout << res[maxLenth] << endl;
// tmpSum;
res[maxLenth] = '0' + (tmpSum % 2);
//cout << "aa" << res[maxLenth] << endl;
--posA, --posB, --maxLenth;
// carry = 0;
}
string::iterator it = res.begin();
while (*it == '0'){
++it;
}
//cout << res[0] << endl;
//cout << "zz" << res.size() << endl;
return it == res.end() ? "0" : string(it, res.end());
}
};
本文介绍了一种使用C++实现的二进制字符串加法的方法。通过模拟二进制加法的过程,该方法能够处理不同长度的二进制字符串,并返回它们相加后的结果。
519

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



