题目:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
从右向左逐位相加,而后进位;
代码:
class Solution {
public:
string addBinary(string a, string b) {
string result = "";//结果字符串
int alen = a.length();//获取字符创长度
int blen = b.length();
if(alen==0&&blen==0)
{
return result;
}
if(alen==0) return b;
if(blen==0) return a;
int plus = 0;//用于进位
while(alen>0 || blen>0)//保证遍历完最长的字符串
{
int sum=0;
if(alen>0) sum += (int)a[alen-1]-48;
if(blen>0) sum += (int)b[blen-1]-48;
sum += plus;//计算相应位相加和
if(sum%2==0)
result = "0" + result;//得到结果
else
result = "1" + result;//得到结果
plus = sum/2;//得到进位
alen--;
blen--;
}
if(plus!=0)
{
result = "1" + result;
}
return result;
}
};