-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path26_add-binary.cpp
More file actions
84 lines (74 loc) · 2.01 KB
/
26_add-binary.cpp
File metadata and controls
84 lines (74 loc) · 2.01 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class Solution {
public:
string addBinary(string a, string b) {
string ans = "";
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int a1 = a.length();
int b1 = b.length();
int carry = 0;
for(int i=0; i < min(a1, b1); i++){
int t1 = a[i] - '0';
int t2 = b[i] - '0';
int sum = t1 + t2 + carry;
if(sum == 3){
ans += '1';
carry = 1;
}
else if(sum == 2){
ans += '0';
carry = 1;
}
else{
carry = 0;
char temp = sum + '0';
ans += temp;
}
}
if(a1 == b1){
if(carry != 0) ans += (carry + '0');
}
if(a1 > b1){
for(int i=b1; i<a1; i++){
int t1 = a[i] - '0';
int sum = t1 + carry;
if(sum == 3){
ans += '1';
carry = 1;
}
else if(sum == 2){
ans += '0';
carry = 1;
}
else{
carry = 0;
char temp = sum + '0';
ans += temp;
}
}
if(carry != 0) ans += (carry + '0');
}
else if(a1 < b1){
for(int i=a1; i<b1; i++){
int t1 = b[i] - '0';
int sum = t1 + carry;
if(sum == 3){
ans += '1';
carry = 1;
}
else if(sum == 2){
ans += '0';
carry = 1;
}
else{
carry = 0;
char temp = sum + '0';
ans += temp;
}
}
if(carry != 0) ans += (carry + '0');
}
reverse(ans.begin(), ans.end());
return ans;
}
};