-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path67. Add Binary.cpp
50 lines (42 loc) · 1.11 KB
/
67. Add Binary.cpp
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
50
/*
Problem : https://leetcode.com/problems/add-binary/
Author : Sabbir Musfique
Time Complexity : O(N)
Space Complexity : O(1)
*/
class Solution {
public:
string addBinary(string a, string b) {
string sb = "";
int i = a.size() - 1;
int j = b.size() - 1;
int carry = 0;
while (i >= 0 || j >= 0) {
if (i >= 0 && j >= 0) {
int sum = (a[i] - '0') + (b[j] - '0') + carry;
if(sum&1) sb += '1';
else sb += '0';
carry = sum / 2;
i--;
j--;
} else if (i >= 0) {
int sum = (a[i]- '0') + carry;
if(sum&1) sb += '1';
else sb += '0';
carry = sum / 2;
i--;
} else {
int sum = (b[j] - '0') + carry;
if(sum&1) sb += '1';
else sb += '0';
carry = sum / 2;
j--;
}
}
if (carry > 0) {
sb += '1';
}
reverse(sb.begin(), sb.end());
return sb;
}
};