-
Notifications
You must be signed in to change notification settings - Fork 0
/
Question80.cpp
65 lines (63 loc) · 1.39 KB
/
Question80.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
58
59
60
61
62
63
64
65
80 -> Add Binary
Solution :
class Solution {
public:
string addBinary(string a, string b) {
int i=a.length()-1;
int j=b.length()-1;
int carry=0;
string s="";
while(i>=0&&j>=0){
int ans=(a[i]-'0')+(b[j]-'0')+carry;
if(ans>=2){
ans=ans-2;
char ch=ans+'0';
s=s+ch;
carry=1;
}
else{
char ch=ans+'0';
s=s+ch;
carry=0;
}
i--;j--;
}
while(j>=0){
int ans=carry+(b[j]-'0');
if(ans>=2){
ans=ans-2;
char ch=ans+'0';
s=s+ch;
carry=1;
}
else{
char ch=ans+'0';
s=s+ch;
carry=0;
}
j--;
}
while(i>=0){
int ans=carry+(a[i]-'0');
if(ans>=2){
ans=ans-2;
char ch=ans+'0';
s=s+ch;
carry=1;
}
else{
char ch=ans+'0';
s=s+ch;
carry=0;
}
i--;
}
if(carry==1){
char ch=carry+'0';
s=s+ch;
carry=0;
}
reverse(s.begin(),s.end());
return s;
}
};