问题描述:
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"
题源:here;完整实现:here
思路:
先将a
,b
对齐,然后相加。因为对齐后不需要在循环中再进行判断,所以效率会高一些。代码如下:
class Solution {
public:
string addBinary(string a, string b) {
while (a.size() != b.size()){
if (a.size() > b.size()) b.insert(b.begin(), '0');
else a.insert(a.begin(), '0');
}
int carryBit = 0;
for (int i = a.size()-1; i >= 0; i--){
int tSum = a[i] - '0' + b[i] - '0'+carryBit;
a[i] = tSum % 2 + '0'; carryBit = tSum / 2;
}
if (carryBit) a.insert(a.begin(), '1');
return a;
}
};
贴出运行结果纪念一下: