-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddBinary.cpp
More file actions
47 lines (40 loc) · 1.13 KB
/
AddBinary.cpp
File metadata and controls
47 lines (40 loc) · 1.13 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
class Solution {
public:
string addBinary(string a, string b) {
string Sol = "";
int A = a.length();
int B = b.length();
if(A>B){
for(int i=0; i<A-B; i++){
b.insert(0, "0");
}
} else if(B>A){
for(int i=0; i<B-A; i++){
a.insert(0, "0");
}
}
cout<<a<<endl<<b<<endl;
int Carry = 0;
for(int i=a.length()-1; i>=0; i--){
if((a[i] - 47) + (b[i] - 47) + Carry == 0){
Sol.insert(0, "0");
}
if((a[i] - 47) + (b[i] - 47) + Carry == 1 && Carry == 1){
Sol.insert(0, "1");
Carry = 0;
}
if((a[i] - 47) + (b[i] - 47) + Carry == 2){
Sol.insert(0, "0");
Carry = 1;
}
if((a[i] - 47) + (b[i] - 47) + Carry == 3){
Sol.insert(0, "1");
Carry = 1;
}
}
if(Carry){
Sol.insert(0, "1");
}
return Sol;
}
};