forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd-binary(AC).cpp
More file actions
44 lines (40 loc) · 775 Bytes
/
add-binary(AC).cpp
File metadata and controls
44 lines (40 loc) · 775 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
#include <algorithm>
using namespace std;
class Solution {
public:
/**
* @param a a number
* @param b a number
* @return the result
*/
string addBinary(string& a, string& b) {
if (a.length() < b.length()) {
return addBinary(b, a);
}
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
string s = "";
int c = 0;
int al = a.length();
int bl = b.length();
int i;
for (i = 0; i < bl; ++i) {
s.push_back(c + a[i] - '0' + b[i] - '0');
c = s[i] >> 1;
s[i] &= 1;
}
for (i = bl; i < al; ++i) {
s.push_back(c + a[i] - '0');
c = s[i] >> 1;
s[i] &= 1;
}
if (c) {
s.push_back(1);
}
for (i = 0; i < s.length(); ++i) {
s[i] += '0';
}
reverse(s.begin(), s.end());
return s;
}
};