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"
题目链接:https://leetcode.com/problems/add-binary/
思路:之前做过大数相乘,这把遇到了大数相加,虽然是二进制版本的,但原理一样
class Solution {
public:
string addBinary(string a, string b) {
int len1=a.length(),len2=b.length();
string res="";
int t=0,c=0,n=min(len1,len2);
for(int i=1;i<=n;i++)
{
t=(c+a[len1-i]+b[len2-i]-96);
c=t/2;
res+=(t%2+48);
}
if(len1>=len2)
{
for(int i=len1-n-1;i>=0;i--)
{
t=(c+a[i]-48);
c=t/2;
res+=t%2+48;
}
}
else
{
for(int i=len2-n-1;i>=0;i--)
{
t=(c+b[i]-48);
c=t/2;
res+=t%2+48;
}
}
if(c)
res+="1";
char ch;
int len=res.length();
for(int i=0;i<len/2;i++)
{
ch=res[i];
res[i]=res[len-1-i];
res[len-1-i]=ch;
}
return res;
}
};
也看了一下网上比较短的代码,可以学习一下
class Solution {
public:
string addBinary(string a, string b) {
string re;
int c=0;
int i=a.size()-1,j=b.size()-1;
while(i>=0||j>=0||c!=0){
int f = i>=0?a[i]-'0':0;
int s = j>=0?b[j]-'0':0;
int cur = f+s+c;
if(cur>1)
c=1;
else
c=0;
if(cur==0||cur==2)
re="0"+re;
else
re="1"+re;
i--,j--;
}
return re;
}
};
参考链接:https://leetcode.com/problems/add-binary/discuss/219381/Short-and-Fast-C%2B%2B-Sol