forked from Wins0n/LeetCode
/
addBinary.cpp
77 lines (72 loc) · 1.47 KB
/
addBinary.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <string>
#include <algorithm>
class Solution
{
public:
std::string addBinary(std::string a, std::string b)
{
std::string res;
int carry = 0;
int i = a.length() - 1;
int j = b.length() - 1;
while (i >= 0 && j >= 0)
{
char ch = a[i] + b[j] - '0' + carry;
if (ch >= '2')
{
ch -= 2;
carry = 1;
}
else
{
carry = 0;
}
res.push_back(ch);
--i;
--j;
}
while (i >= 0)
{
char ch = a[i] + carry;
if (ch >= '2')
{
ch -= 2;
carry = 1;
}
else
{
carry = 0;
}
res.push_back(ch);
--i;
}
while (j >= 0)
{
char ch = b[j] + carry;
if (ch >= '2')
{
ch -= 2;
carry = 1;
}
else
{
carry = 0;
}
res.push_back(ch);
--j;
}
if (carry)
{
res.push_back('1');
}
std::reverse(res.begin(), res.end());
return res;
}
};
int main(int argc, char** argv)
{
Solution sln;
std::cout << sln.addBinary("1111", "1111") << std::endl;
return 0;
}