题目描述
Given two binary strings a and b, return their sum as a binary string.
中文:给定两个二进制的字符串,计算他们的加法和,结果以字符串返回
知识点:
1.字符转数字:该字符 - ‘0’
2.二进制加法
3.进位处理
方法1:
思路:将短字符串前面补零,从后往前对应相加,
二进制加法:
1+1=10,1+1+1=11
十进制加法:
结果有四种情况:0、1、2、3 后两种需要将进位标志设置为1.
class Solution {
public:
string addBinary(string a, string b) {
int a_len = a.size();
int b_len = b.size();
string re="";
if(a_len > b_len)
{
for(int i=0;i<a_len-b_len;i++)
{
b = '0' + b;
}
}else{
for(int i=0;i<b_len-a_len;i++)
{
a = '0' + a;
}
}
int carry = 0;
for(int j=a.size()-1;j>=0;j--)
{
int tmp;
tmp = (a[j]-'0')+(b[j]-'0')+carry;
if(tmp == 0)
{
re = '0' + re;
carry = 0;
}
if(tmp == 1)
{
re = '1' + re;
carry = 0;
}
if(tmp == 2)
{
re = '0' + re;
carry = 1;
}
if(tmp == 3)
{
re = '1' + re;
carry = 1;
}
}
if(carry)
{
re = '1' + re;
}
return re;
}
};
方法2:
这种方法就是使用数组,从后往前遍历,不齐补零,商表进位,余数表示相加结果值;
class Solution {
public:
string addBinary(string a, string b) {
int a_len = a.size()-1;
int b_len = b.size()-1;
string re = "";
int carry = 0;
while(a_len>=0 || b_len>=0)
{
int p_a = a_len>=0? a[a_len--]-'0':0;
int p_b = b_len>=0? b[b_len--]-'0':0;
int sum = p_a + p_b + carry;
carry = sum / 2;
re = to_string(sum%2) + re;
}
return carry==1?"1"+re:re;
}
};