-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0067-add-binary.cpp
More file actions
50 lines (31 loc) · 809 Bytes
/
Copy path0067-add-binary.cpp
File metadata and controls
50 lines (31 loc) · 809 Bytes
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
class Solution {
public:
string addBinary(string a, string b) {
int n=a.length();
int m=b.length();
if(n<m){
a.insert(0,m-n,'0');
}else if(n>m){
b.insert(0,n-m,'0');
}
string ans="";
int carry=0;
n=a.length();
for(int i=n-1;i>=0;i--){
int sum=0;
if(a[i]=='1' && b[i]=='1'){
sum=2+carry;
cout<<"if sum"<<sum<<endl;
}else{
sum=(a[i]-'0')+(b[i]-'0')+carry;
}
ans.push_back((sum%2)+'0');
carry=sum/2;
}
if(carry){
ans.push_back('1');
}
reverse(ans.begin(),ans.end());
return ans;
}
};