leetcode67.二进制求和

1.题目
给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1 和 0。
2.示例
示例 1:
输入: a = “11”, b = “1”
输出: “100”
示例 2:
输入: a = “1010”, b = “1011”
输出: “10101”
3.思路
不建议转十进制数字求和再转为二进制,会超时。
二进制求和,从右向左开始计算
4.代码
string addBinary(string a, string b) {
stack< bool> s;//存储结果
int cur_a=a.size()-1;
int cur_b=b.size()-1;
int carry=0; //进位
while(cur_a>=0||cur_b>=0){
int val_a=0;
if(cur_a>=0)
val_a=a[cur_a–]-‘0’;
int val_b=0;
if(cur_b>=0)
val_b=b[cur_b–]-‘0’;
int tmp=val_a+val_b+carry;
s.push(tmp%2);
carry=tmp/2;
}
if(carry==1)
s.push(1);
string res;
while(!s.empty()){
res.push_back(booltochar(s.top()));
s.pop();
}
return res;
}
char booltochar(bool b){
if(b) return ‘1’;
else return ‘0’;
}

猜你喜欢

转载自blog.csdn.net/qq_14962179/article/details/85561756