-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathLeetCode#55.cc
40 lines (32 loc) · 889 Bytes
/
LeetCode#55.cc
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
class Solution {
public:
string addBinary(string a, string b) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
string ret = "";
reverse(a.begin(),a.end());
reverse(b.begin(),b.end());
int c = 0;
int i;
for(i=0;i<a.length()&&i<b.length();i++){
int t = c + (a[i]=='1') + (b[i]=='1');
ret+=('0'+t%2);
c=t/2;
}
while(i<a.length()){
int t = c+(a[i]=='1');
ret+=('0'+t%2);
c=t/2;
i++;
}
while(i<b.length()){
int t= c+(b[i]=='1');
ret+=('0'+t%2);
c=t/2;
i++;
}
if(c) ret+="1";
reverse(ret.begin(),ret.end());
return ret;
}
};