67. Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
思路:
1.将两个字符串按数组相加得到新数组。
2.将新数组转换成结果。
代码如下:
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
|
class
Solution {
public
:
string addBinary(string a, string b) {
int
sizeA = a.size();
int
sizeB = b.size();
int
carry = 0;
vector<
int
> result;
string resultStr;
if
(sizeA < sizeB)
return
addBinary(b, a);
for
(
int
i = 0; i < sizeB; i++)
{
int
cur = (a[sizeA - i - 1] -
'0'
) + (b[sizeB - i - 1] -
'0'
) + carry;
if
(cur < 2)
{
result.push_back(cur);
carry = 0;
}
else
if
(cur == 2)
{
result.push_back(0);
carry = 1;
}
else
if
(cur == 3)
{
result.push_back(1);
carry = 1;
}
}
for
(
int
j = sizeB; j < sizeA; j++)
{
int
cur = (a[sizeA - j - 1] -
'0'
) + carry;
if
(cur < 2)
{
result.push_back((a[sizeA - j - 1] -
'0'
) + carry);
carry = 0;
}
else
if
(cur == 2)
{
result.push_back(0);
carry = 1;
}
else
if
(cur == 3)
{
result.push_back(1);
carry = 1;
}
}
if
(carry == 2)
{
result.push_back(0);
result.push_back(1);
}
else
if
( carry == 1)
{
result.push_back(1);
}
for
(
int
k = 0; k < result.size(); k++)
{
if
(result[result.size() - 1 - k] == 1)
{
resultStr.append(1,
'1'
);
}
else
{
resultStr.append(1,
'0'
);
}
}
return
resultStr;
}
};
|
本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1836715