LeetCode_67_二进制求和
廖家龙 用心听,不照做

题目描述:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
给你两个二进制字符串,返回它们的和(用二进制表示)。输入为 非空 字符串且只包含数字 1 和 0。

示例:

输入: a = "11", b = "1"
输出: "100"

输入: a = "1010", b = "1011"
输出: "10101"

提示:
1. 每个字符串仅由字符 '0' 或 '1' 组成。
2. 1 <= a.length, b.length <= 10^4
3. 字符串如果不是 "0" ,就都不含前导零。

解法1:逐项求和

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
string addBinary(string num1, string num2) {

string res = "";

int i1 = num1.length() - 1, i2 = num2.length() - 1;
int carry = 0;

while (i1 >= 0 || i2 >= 0) {

int x = i1 >= 0 ? num1[i1] - '0' : 0;
int y = i2 >= 0 ? num2[i2] - '0' : 0;

int sum = x + y + carry;

res.push_back('0' + sum % 2);

carry = sum / 2;

i1--;
i2--;
}

if (carry != 0) res.push_back('0' + carry);

reverse(res.begin(), res.end());

return res;
}
};