forked from timoncui/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd_Binary.cpp
More file actions
49 lines (44 loc) · 1.17 KB
/
Add_Binary.cpp
File metadata and controls
49 lines (44 loc) · 1.17 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
47
48
49
/*
Author: Timon Cui, [email protected]
Title: Add Binary
Description:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
Difficulty rating: Easy
Notes: Could convert to unit, perform addition, then convert back, but won't be able to handle long inputs.
*/
class Solution {
public:
int MakeFirstLonger(string& a, string& b) {
if (a.length() < b.length()) swap(a, b);
return a.length() - b.length();
}
string And(string a, string b) {
int offset = MakeFirstLonger(a, b);
string c = b;
for (int i = 0; i < b.length(); ++i) {
if (a[i + offset] == '0') c[i] = '0';
}
return c;
}
string Xor(string a, string b) {
int offset = MakeFirstLonger(a, b);
string c = a;
for (int i = 0; i < b.length(); ++i) {
c[i + offset] = a[i + offset] != b[i] ? '1' : '0';
}
return c;
}
string addBinary(string a, string b) {
string c = And(a, b), s = Xor(a, b);
while (c.find('1') != string::npos) {
string t = c.substr(c.find('1'), c.length()) + "0";
c = And(s, t);
s = Xor(s, t);
}
return s;
}
};