题目描述:
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1
or 0
.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
二进制数相加,模拟竖式加减,注意进位即可。
class Solution {
public:
string addBinary(string a, string b) {
int i=a.length()-1;
int j=b.length()-1;
string result;
int carry=0;
while(i>=0&&j>=0)
{
int sum=(a[i]-'0')+(b[j]-'0')+carry;
if(sum<=1)
{
carry=0;
result=(char)(sum+'0')+result;
}
else if(sum>1)
{
carry=1;
result=(char)(sum-2+'0')+result;
}
i--;
j--;
}
if(a.length()>=b.length())
{
int k=a.length()-b.length()-1;
while(k>=0)
{
int sum=(a[k]-'0')+carry;
if(sum<=1)
{
carry=0;
result=(char)(sum+'0')+result;
}
else if(sum>1)
{
carry=1;
result=(char)(sum-2+'0')+result;
}
k--;
}
}
else if(b.length()>a.length())
{
int k=b.length()-a.length()-1;
while(k>=0)
{
int sum=(b[k]-'0')+carry;
if(sum<=1)
{
carry=0;
result=(char)(sum+'0')+result;
}
else if(sum>1)
{
carry=1;
result=(char)(sum-2+'0')+result;
}
k--;
}
}
if(carry==1) result='1'+result;
return result;
}
};