67. Add Binary
一、问题描述
Given two binary strings, return their sum (also a binary string).
二、输入输出
For example,
a = "11"
b = "1"
Return "100"
.
三、解题思路
从后向前遍历
- 这道题看着不难,有几个点需要注意。首先最好不要转换成int或者二进制的数来进行计算,再转换回去。有可能需要处理越界的问题,如果是两个int的相加基本上一定有让你越界的测试案例,即使你用的是longlong。另外,要注意最高位需要进位的情况,这种情况比较容易落下,一般人遍历完两个数组也就停止了。
- 思路:从后向前按位相加,主要int和char的转换。单独的记录下来是否需要进位。一旦有一个string遍历完了,就停,然后把另外一个和进位加起来添加到结果中。最后处理最高位需要进位的情况。还是比较简单。
class Solution {
public:
string addBinary(string a, string b) {
string ret;
int increaseBit = 0;
int i, j;
for (i = a.size()-1, j = b.size()-1; i>=0 && j>=0 ; --i,--j) {
int sum = a[i]-'0' + b[j]-'0' + increaseBit;
if(sum < 2) {ret.insert(ret.begin(), sum+'0');increaseBit = 0;}
else {ret.insert(ret.begin(), sum % 2+'0'); increaseBit = 1;}
}
if(increaseBit){
while(i>=0){
int sum = a[i]-'0' + increaseBit;
if(sum < 2){ret.insert(ret.begin(), sum+'0');increaseBit = 0;}
else{ret.insert(ret.begin(),sum % 2 + '0'); increaseBit = 1;}
i--;
}
while(j>=0){
int sum = b[j]-'0' + increaseBit;
if(sum < 2){ret.insert(ret.begin(), sum+'0'); increaseBit = 0;}
else {ret.insert(ret.begin(), sum % 2+'0'); increaseBit = 1;}
j--;
}
}else{
if(i>=0)ret.insert(ret.begin(),a.begin(), a.begin()+i+1);
if(j>=0)ret.insert(ret.begin(), b.begin(), b.begin()+j+1);
}
if(increaseBit){
ret.insert(ret.begin(), '1');
}
return ret;
}
};