-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd-binary.cpp
More file actions
62 lines (49 loc) · 1.38 KB
/
add-binary.cpp
File metadata and controls
62 lines (49 loc) · 1.38 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
//
// Created by Chenguang Wang on 2024/1/23.
//
// https://leetcode.cn/problems/add-binary/
#include <string>
using namespace std;
class Solution {
public:
string addBinary(string a, string b) {
string ans;
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int n = max(a.size(), b.size()), carry = 0;
for (size_t i = 0; i < n; ++i) {
carry += i < a.size() ? (a.at(i) == '1') : 0;
carry += i < b.size() ? (b.at(i) == '1') : 0;
ans.push_back((carry % 2) ? '1' : '0');
carry /= 2;
}
if (carry) {
ans.push_back('1');
}
reverse(ans.begin(), ans.end());
return ans;
}
string addBinary2(string a, string b) {
string result;
int i = a.size() - 1;
int j = b.size() - 1;
int carry = 0;
while (i >= 0 || j >= 0 || carry > 0) {
int sum = carry;
// 只有当字符是 '1' 时才加 1
if (i >= 0 && a[i] == '1') {
sum += 1;
}
if (j >= 0 && b[j] == '1') {
sum += 1;
}
result.push_back((sum % 2) == 1 ? '1' : '0');
// 更新进位
carry = sum / 2;
--i;
--j;
}
reverse(result.begin(), result.end());
return result;
}
};