-
Notifications
You must be signed in to change notification settings - Fork 213
/
AddBinary.h
37 lines (35 loc) · 901 Bytes
/
AddBinary.h
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
/*
Author: Annie Kim, [email protected]
Date: Apr 17, 2013
Update: Sep 25, 2013
Problem: Add Binary
Difficulty: Easy
Source: http://leetcode.com/onlinejudge#question_67
Notes:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
Solution: '1'-'0' = 1.
*/
class Solution {
public:
string addBinary(string a, string b) {
int N = a.size(), M = b.size(), K = max(N, M);
string res(K, ' ');
int carry = 0;
int i = N-1, j = M-1, k = K-1;
while (i >= 0 || j >= 0)
{
int sum = carry;
if (i >= 0) sum += a[i--] - '0';
if (j >= 0) sum += b[j--] - '0';
carry = sum / 2;
res[k--] = sum % 2 + '0';
}
if (carry == 1)
res.insert(res.begin(), '1');
return res;
}
};