67. Add Binary
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
.
解题思路:
1)将每一位字符都转换为数字,将两个字符串对应位的数字相加。若需要进位,则保存进位的值并在下一次相加时加上进位。对应位若不存在则设为0,相加。
2)若两个字符串所有对应位相加结束,判断最后一个进位是否为1,若为1,则在字符串最前面补1.
C++代码如下:
class Solution {
public:
string addBinary(string a, string b) {
int n=a.length()-1;
int m=b.length()-1;
int p=0;
string c="" ;
while(n>=0 || m>=0){
int i= n>=0 ? a[n--]-‘0‘:0;
int j= m>=0 ? b[m--]-‘0‘:0;
int sum=i+j+p;
c=to_string(sum%2)+c;
p=sum/2;
}
c= p==1 ? ‘1‘+c :c;
return c;
}
};
原文地址:https://www.cnblogs.com/ssml/p/9301825.html