Description
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"
分析一
- 思路很简单,对a,b从后往前遍历进行加法运算,然后把结果存入栈中,以栈出来的顺序拼接成字符串就是结果了。
C++实现1
class Solution {
public:
string addBinary(string a, string b) {
stack<int> s;
int s1=a.length();
int s2=b.length();
int i=s1-1;
int j=s2-1;
int carry=0;
while(i>=0||j>=0||carry>0){
int n1=i>=0 ? a[i--]-'0':0;
int n2=j>=0 ? b[j--]-'0':0;
int c=carry+n1+n2;
s.push(c%2);
carry=c/2;
}
string res="";
while(!s.empty()){
res+=s.top()+'0';
s.pop();
}
return res;
}
};
C++实现2
- 首先要用0把两个字符串补齐,补齐之后,从最后一位进行二进制的加法运算。
代码二
class Solution {
public:
string addBinary(string a, string b) {
int a1_len=a.length()-1;
int b1_len=b.length()-1;
while(a.length()>b.length()){
b='0'+b;
}
while(b.length()>a.length()){
a='0'+a;
}
string s1;
char flag='0';
for(int i=a.length()-1;i>=0;i--){
int ch=a[i]-'0'+b[i]-'0'+flag-'0';
if(ch==3){
s1='1'+s1;
flag='1';
}else if(ch==2){
s1='0'+s1;
flag='1';
}else{
char c=ch+'0';
s1=c+s1;
flag='0';
}
}
if(flag=='1'){
s1='1'+s1;
}
return s1;
}
};
Python实现
思路很粗暴,直接转换成二进制做处理即可。
class Solution:
def addBinary(self, a: str, b: str) -> str:
x, y = int(a,2), int(b,2)
while y:
ans = x^y
carry = (x&y)<<1
x,y = ans, carry
return bin(x)[2:]
下面是一个标准模板的遍历做法:
class Solution:
def addBinary(self, a: str, b: str) -> str:
m = len(a)
n = len(b)
i = m-1
j = n-1
carry = 0
res = ""
while i>=0 or j>=0:
if i>=0:
carry+=int(a[i])
i-=1
if j>=0:
carry+=int(b[j])
j-=1
res = str(carry%2)+res
carry = carry//2
if carry:
res=str(carry)+res
return res