用字符串表示二进制加法。
逻辑很简单了,不过要注意s1、s2长短不一时是否有进位的处理。本来还是用c写的,要返回char *所以肯定要calloc,但是leet上凡是c我用到calloc的少有不runtime error的,所以换成c++,用string就更简单了。
c++如下:
class Solution_AddBinary {
public:
string addBinary(string a, string b) {
string result;
int alength = a.length() - 1;
int blength = b.length() - 1;
int sum = 0, plus = 0;
int suma = 0, sumb = 0;
string c;
while (alength >= 0 || blength >= 0) {
if (alength >= 0)
suma = a[alength];
else
suma = '0';
if (blength >= 0)
sumb = b[blength];
else
sumb = '0';
sum = suma - '0' + sumb - '0' + plus;
plus = sum / 2;
sum = sum % 2;
c = sum + '0';
result.insert(0, c);
alength--, blength--;
}
if (plus)
result.insert(0, "1");
return result;
}
};