67. Add Binary
给定两个二进制字串 a, b,
求 a+b 的后的二进制字串。
Example 1:
Input: a = "11", b = "1"
Output: "100"
Explanation: a = 3, b = 1, 相加后为 4 (100)
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Explanation: a = 10, b = 11, 相加后为 21 (10101)
解题思路:
很基本的大数运算,
直接拿两个二进制字串做直式加法就行了,
先把字串反转后对齐末端,
从后面开始做加法再看要不要进位,
最后再把答案反转过来。
C++ code:
class Solution {
public:
string addBinary(string a, string b) {
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int size = max(a.size(), b.size());
string c(size + 1, '0');
for(int i = 0; i < size; i++){
if(i < a.size()) c[i] += a[i] - '0';
if(i < b.size()) c[i] += b[i] - '0';
if(c[i] > '1'){
c[i] -= 2;
c[i+1] += 1;
}
}
if(c.back() == '0') c.pop_back();
reverse(c.begin(), c.end());
return c;
}
};