我写了……一个……很长的代码……唉,我先把短的那个数字补齐,也就是前面缺的那几位补0,然后再加。
注意
result = char('0' + rx % 2) + result;
这里面这个强制类型转换是必须必的。不然会报错。
class Solution {
public:
string addBinary(string a, string b) {
int x = 0;
string result = "";
int an = a.size();
int bn = b.size();
if(an > bn)
{
for(int i = 0; i < an - bn; ++i)
{
b = '0' + b;
}
}
else
{
for(int i = 0; i < bn - an; ++i)
{
a = '0' + a;
}
}
for(int i = a.size() - 1; i >= 0; --i)
{
int rx = (a[i] - '0') + (b[i] - '0') + x;
if(rx >= 2)
x = 1;
else
x = 0;
result = char('0' + rx % 2) + result;
}
if(x == 1)
result = '1' + result;
return result;
}
};
看看别人写的,再看看我写的……简直是垃圾。
class Solution {
public:
string addBinary(string a, string b) {
string s = "";
int c = 0, i = a.size() - 1, j = b.size() - 1;
while(i >= 0 || j >= 0 || c == 1)
{
c += i >= 0 ? a[i --] - '0' : 0;
c += j >= 0 ? b[j --] - '0' : 0;
s = char(c % 2 + '0') + s;
c /= 2;
}
return s;
}
};