-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathadd_binary.cpp
More file actions
41 lines (31 loc) · 777 Bytes
/
add_binary.cpp
File metadata and controls
41 lines (31 loc) · 777 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
class Solution {
public:
string addBinary(string a, string b) {
string result;
int bit;
int flag = 0;
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
const char *a_str = a.c_str();
const char *b_str = b.c_str();
while ((*a_str != '\0') && (*b_str != '\0')) {
bit = (*a_str - '0') + (*b_str - '0') + flag;
result.push_back((bit % 2) + '0');
flag = bit / 2;
++a_str;
++b_str;
}
const char *p = ('\0' == *a_str) ? b_str : a_str;
while (*p != '\0') {
bit = (*p - '0') + flag;
result.push_back((bit % 2) + '0');
flag = bit / 2;
++p;
}
if (flag > 0) {
result.push_back('1');
}
reverse(result.begin(), result.end());
return result;
}
};