-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddBinary.cpp
61 lines (54 loc) · 1.22 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
#include<iostream>
#include<string>
using namespace std;
string addBinary(string a, string b)
{
string result;
int carry = 0;
int index_a = a.size() - 1, index_b = b.size() - 1;
while(index_a >= 0 && index_b >= 0)
{
int i = a[index_a] - 48;
int j = b[index_b] - 48;
char c = (i + j + carry) % 2 + 48;
carry = (i + j + carry) / 2;
result.push_back(c);
--index_a; --index_b;
}
cout << "reverse s1 : " << result << endl;
//单层遍历
while(index_a >= 0)
{
int i = a[index_a] - 48;
char c = (i + carry) % 2 + 48;
carry = (i + carry) / 2;
result.push_back(c);
--index_a;
}
while(index_b >= 0)
{
int i = b[index_b] - 48;
char c = (i + carry) % 2 + 48;
carry = (i + carry) / 2;
result.push_back(c);
--index_b;
}
if(carry == 1)
{
result.push_back((char)carry + 48);
}
cout << "result : " << result << endl;
string s;
for(int i = result.size() - 1; i >= 0; --i)
{
s.push_back(result[i]);
}
return s;
}
int main()
{
string a = "101";
string b = "101";
cout << addBinary(a, b) << endl;
return 0;
}