class Solution {
//this is a very simple implementation
//should practice a lot
public:
string addBinary(string a, string b) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int carry = 0;
int p = a.size()-1;
int q = b.size()-1;
string ans;
while (p >= 0 || q >= 0 || carry)
{
int a_val = (p >= 0 ? a[p]-'0' : 0);
int b_val = (q >= 0 ? b[q]-'0' : 0);
int now = carry+a_val+b_val;
int tmp = now%2;
carry = now/2;
ans.insert(ans.begin(), tmp+'0');
p = (p >= 0 ? --p : p);
q = (q >= 0 ? --q : q);
}
return ans;
}
};
second time
class Solution {
public:
string addBinary(string a, string b) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int carry = 0;
int i = 0;
int j = 0;
string ans;
while(i < a.size() || j < b.size() || carry != 0)
{
int tmp1 = 0;
int tmp2 = 0;
if(i < a.size()) tmp1 = a[i]-'0', i++;
if(j < b.size()) tmp2 = b[j]-'0', j++;
int sum = tmp1+tmp2+carry;
ans.push_back(sum%2+'0');
carry = sum/2;
}
reverse(ans.begin(), ans.end());
return ans;
}
};
本文介绍了一种使用C++实现的二进制数相加的方法。通过反转字符串并逐位进行运算的方式,有效地处理了不同长度的二进制数相加的问题,并通过携带进位实现了准确的二进制加法。
1932

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



