-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathadd-binary(AC).cpp
More file actions
45 lines (40 loc) · 1021 Bytes
/
add-binary(AC).cpp
File metadata and controls
45 lines (40 loc) · 1021 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
#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 al = a.length();
int bl = b.length();
int i;
for (i = 0; i < bl; ++i) {
s.push_back(a[i] + b[i] - '0');
}
for (i = bl; i < al; ++i) {
s.push_back(a[i]);
}
int c = 0;
for (i = 0; i < al - 1; ++i) {
c = s[i] - '0' >> 1;
s[i] = (s[i] - '0' & 1) + '0';
s[i + 1] += c;
}
c = s[i] - '0' >> 1;
s[i] = (s[i] - '0' & 1) + '0';
if (c) {
s.push_back('1');
}
reverse(s.begin(), s.end());
return s;
}
};