67. Add Binary
我的思路:
直接两个字符串按尾对齐,然后模拟加法就好了。只要细心一点应该是没有问题的。
我的代码:
class Solution {
public:
string addBinary(string a, string b) {
string res = "";
int la = a.size();
int lb = b.size();
// let la >= lb
if(la < lb) {
string t = a;
a = b;
b = t;
}
la = a.size();
lb = b.size();
int ia;
int ib;
int carry = 0;
for(int i = lb - 1; i >= 0; i--) {
ia = a[la - lb + i] - '0';
ib = b[i] - '0';
if(ia + ib + carry > 1) {
res = (char)(ia + ib + carry - 2 + '0') + res;
carry = 1;
} else {
res = (char)(ia + ib + carry + '0') + res;
carry = 0;
}
}
for(int i = la - lb - 1; i >= 0; i--) {
ia = a[i] - '0';
if(ia + carry > 1) {
res = (char)(ia + carry - 2 + '0') + res;
carry = 1;
} else {
res = (char)(ia + carry + '0') + res;
carry = 0;
}
}
if(carry) {
res = "1" + res;
}
return res;
}
};
最快解法的代码:
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;
}
};
首先思路是差不多的,其次,这份代码比我的要简洁一些,因为这份代码很好地将三种情况结合在了一起。在我的代码中,三种情况分别是第1个for循环,第2个for循环,以及最后一个if。但是运行速度好像差的有点多,我尝试着把输出语句去掉,然后就和最快解法一样快了。。。。。。所以说,输出很花费时间。