67. Add Binary
Easy
814166FavoriteShare
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"
这道题我转成int,会溢出,看来它是希望我直接用string来算。
出错的时候是这样的:
Last executed input:(这个testcase太狠了,有800多个位)
"10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101"
"110101001011101110001111100110001010100001101
011101010000011011011001011101111001100000011011110011"
Line 15: Char 16: runtime error: signed integer overflow: 1347006986 * 2 cannot be represented in type 'int' (solution.cpp)
出错时代码如下:
class Solution {
public:
string addBinary(string a, string b) {
int i=a.length();
int j=b.length();
long long A=0;
long long B=0;
long long ans=0;
string ans1="";
string ans2="";
for(int k=0;k<i;k++)
{
A=A*2+a[k]-'0';
}
for(int k=0;k<j;k++)
{
B=B*2+b[k]-'0';
}
ans=A+B;
while(ans>0)
{
if(ans%2==1)ans1+='1';
else ans1+='0';
ans/=2;
}
int y;
for(y=ans1.length()-1;y>=0;y--)
{
ans2+=ans1[y];
}
return ans2;
}
};
然后我用直接string加又写了一遍,AC了。方法是先把ab两补成一样长,然后暴力加,得到ans1是倒着的,再倒一下就好了。
class Solution {
public:
string addBinary(string a, string b) {
int i=a.length();
int j=b.length();
int t0=0;
string t="";
string ans1="";
string ans="";
bool flag=false;
if(i>j)
{
t0=i-j;
for(int k=0;k<t0;k++)
{t+='0';}
b=t+b;
}
else if(i<j)
{
t0=j-i;
for(int k=0;k<t0;k++)
{t+='0';}
a=t+a;
}
//现在两个string一样长了
for(int k=a.length()-1;k>=0;k--)
{
if(a[k]!=b[k]&&flag)ans1+='0';
else if(a[k]!=b[k]&&(!flag))ans1+='1';
else if((a[k]==b[k])&&(a[k]=='0')&&(flag)){ans1+='1';flag=false;}
else if((a[k]==b[k])&&(a[k]=='0')&&(!flag))ans1+='0';
else if((a[k]==b[k])&&(a[k]=='1')&&(flag))ans1+='1';
else if((a[k]==b[k])&&(a[k]=='1')&&(!flag)){ans1+='0';flag=true;}
}
if(flag)ans1+='1';
for(int k=ans1.length()-1;k>=0;k--)
{
ans+=ans1[k];
}
return ans;
}
};