-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddbinary.cpp
57 lines (34 loc) · 1.2 KB
/
addbinary.cpp
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
class Solution {
public:
string addBinary(string a, string b) {
if(b.size() > a.size()) swap(a,b);
while(b.size() < a.size()) b = "0" + b;
int carry = 0;
string res = "";
for(int i = b.size()-1; i >= 0 ; --i)
{
if(b[i] == '1' && a[i]=='1')
{
if(carry == 0) res = "0" + res;
else res = "1" + res;
carry = 1;
}
else if(b[i] =='0' && a[i] =='0')
{
if(carry == 0) res = "0" + res;
else
{
res = "1" + res;
carry = 0;
}
}
else if((b[i]=='0' && a[i]=='1') || (b[i]=='1' && a[i] == '0'))
{
if(carry == 0) res = "1" + res;
else res = "0" + res;
}
}
if(carry == 1) res = "1" + res;
return res;
}
};