题目:
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"
题意:
求两个二进制整数的和
思路:
模拟加法,从低位往高位,注意进位
Code:
class Solution {
public:
string addBinary(string a, string b) {
int n=a.length()-1,m=b.length()-1,k=0;
string c="";
while(n>=0||m>=0||k==1){
int sum=k;
if(n>=0) sum+=(a[n--]-'0');
if(m>=0) sum+=(b[m--]-'0');
c=to_string(sum%2)+c;
k=sum/2;
}
return c;
}
};