-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd_binary.cpp
More file actions
46 lines (43 loc) · 1.29 KB
/
add_binary.cpp
File metadata and controls
46 lines (43 loc) · 1.29 KB
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
#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;
class Solution {
public:
string addBinary(string a, string b) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int a_index = a.length()-1;
int b_index = b.length()-1;
string result="";
int last = 0;
while (a_index >= 0 || b_index >= 0 ) {
char a_value = (a_index >= 0) ? a.at(a_index) : '0';
char b_value = (b_index >= 0) ? b.at(b_index) : '0';
int cur = last + (a_value - '0') + (b_value - '0');
if (cur == 3) {
last = 1;
result.insert(result.begin(), '1');
} else if (cur == 2) {
last = 1;
result.insert(result.begin(), '0');
} else if (cur == 1) {
last = 0;
result.insert(result.begin(), '1');
} else if (cur == 0) {
last = 0;
result.insert(result.begin(), '0');
}
--a_index;
--b_index;
}
if (last == 1) result.insert(result.begin(), '1');
return result;
}
};
int main (int argc, char *argv[]) {
Solution s;
string a = "11110001", b = "100000011111111";
cout << s.addBinary(a, b) << endl;
return 0;
}