-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddBinary*
55 lines (50 loc) · 1.49 KB
/
addBinary*
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
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"
//********************//
class Solution {
public:
string addBinary(string a, string b) {
string res;
int na = a.size();
int nb = b.size();
int n = max(na, nb);
bool carry = false;
if (na > nb) {
for (int i = 0; i < na - nb; ++i) b.insert(b.begin(), '0');
}
else if (na < nb) {
for (int i = 0; i < nb - na; ++i) a.insert(a.begin(), '0');
}
for (int i = n - 1; i >= 0; --i) {
int tmp = 0;
if (carry) tmp = (a[i] - '0') + (b[i] - '0') + 1;
else tmp = (a[i] - '0') + (b[i] - '0');
if (tmp == 0) {
res.insert(res.begin(), '0');
carry = false;
}
else if (tmp == 1) {
res.insert(res.begin(), '1');
carry = false;
}
else if (tmp == 2) {
res.insert(res.begin(), '0');
carry = true;
}
else if (tmp == 3) {
res.insert(res.begin(), '1');
carry = true;
}
}
if (carry) res.insert(res.begin(), '1');
return res;
}
};
//***********
this is not my code ,i can not have an idea to deal with it