题目
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"
Constraints:
Each string consists only of '0' or '1' characters.
1 <= a.length, b.length <= 10^4
Each string is either "0" or doesn't contain any leading zero.
思路
代码
Code 01
class Solution {
public:
string addBinary(string a, string b) {
reverse(a.begin(),a.end()); //从低位开始处理
reverse(b.begin(),b.end());
string c;
int r = 0;
int len = max(a.length(),b.length()); //取较大字符串长度
for(int i=0;i<len;i++){
r+=i<a.length()?a.at(i)=='1':0; //累加a中第i位的数字
r+=i<b.length()?b.at(i)=='1':0; //累加b中第i位的数字
c.push_back(r%2?'1':'0'); // 记录当前和数字
r/=2; //更新当前余数
}
if(r!=0)c.push_back('1'); //处理最高位进位
reverse(c.begin(),c.end()); //存储为低位到高位,反转后为高位到低位
return c;
}
};