# 67. 二进制求和

力扣原题链接(点我直达) (opens new window)

给定两个二进制字符串,返回他们的和(用二进制表示)。

输入为非空字符串且只包含数字 10

示例 1:

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

示例 2:

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

# 第一版,其实不难,仔细一点就可以了

执行用时 :8 ms, 在所有 cpp 提交中击败了48.84%的用户

内存消耗 :8.7 MB, 在所有 cpp 提交中击败了45.19%的用户

    string addBinary(string a, string b) {
	reverse(a.begin(), a.end());
	reverse(b.begin(), b.end());
	if (a.size() < b.size()) swap(a, b);

	vector<char> res;
	int len = b.size(),minus = a.size()-b.size();
	for (int i = 0; i <len; ++i) {
		res.push_back(b[i] - '0' + a[i]);
	}
	//cout << res << endl;
	for (int i = len; i < len+minus; ++i)
		res.push_back(a[i]);
	/*reverse(res.begin(), res.end());
	cout << res << endl;*/
	//for (auto a : res)
	//	cout << a;
	//cout << endl;
	for (int i = 0; i <len+minus-1; ++i) {
		if (res[i] >= '2') {
			res[i + 1] = res[i + 1] + (res[i] - '0')/2;
			res[i] = '0' + (res[i] -'0') % 2;
		}

		//for (auto a : res)
		//	cout << a;
		//cout << endl;
	}
	//cout << res << endl;
	string result;
	for (auto& a : res)
		result += a;

	//cout << result << endl;

	reverse(result.begin(), result.end());
	if (result[0] > '1') {
		result[0] = result[0] -2;
		result = '1' + result;
	}

	//cout << res << endl;
	//while (res[0] > '1') {
	//	res[0] = res[0] - 2;
	//	res = '1' + res;
	//}
	//reverse(res.begin(), res.end());
	return result;
        
    }
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50