-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddBinary-LCQ.cpp
More file actions
41 lines (32 loc) · 827 Bytes
/
AddBinary-LCQ.cpp
File metadata and controls
41 lines (32 loc) · 827 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
/*
Add Binary
Given two binary strings a and b, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Constraints:
1 <= a.length, b.length <= 104
a and b consist only of '0' or '1' characters.
Each string does not contain leading zeros except for the zero itself.
*/
class Solution {
public:
string addBinary(string a, string b) {
string res;
int i = a.size() - 1, j = b.size() - 1, sum = 0, carry = 0;
while (i >= 0 || j >= 0) {
sum = carry;
if (i >= 0) sum += a[i] - '0';
if (j >= 0) sum += b[j] - '0';
carry = sum > 1 ? 1 : 0;
res += to_string(sum % 2);
i--; j--;
}
if (carry) res += to_string(carry);
reverse(res.begin(), res.end());
return res;
}
};