forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd-binary.cpp
More file actions
31 lines (28 loc) · 805 Bytes
/
add-binary.cpp
File metadata and controls
31 lines (28 loc) · 805 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
// Time: O(n)
// Space: O(1)
class Solution {
public:
/**
* @param a a number
* @param b a number
* @return the result
*/
string addBinary(string& a, string& b) {
string result;
int result_length = max(a.length(), b.length()) ;
int carry = 0;
for (int i = 0; i < result_length; ++i) {
int a_bit_i = i < a.length() ? a[a.length() - 1 - i] - '0' : 0;
int b_bit_i = i < b.length() ? b[b.length() - 1 - i] - '0' : 0;
int sum = carry + a_bit_i + b_bit_i;
carry = sum / 2;
sum %= 2;
result.push_back('0' + sum);
}
if (carry) {
result.push_back('0' + carry);
}
reverse(result.begin(), result.end());
return result;
}
};