/
67. Add Binary.cpp
77 lines (67 loc) · 1.76 KB
/
67. Add Binary.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
77
//别人的算法,主要差异在于它的while是用的or,然后再在其中去判断分支,
//a还有位,b还有位,或者有进位[见comment]
#include<iostream>
#include<stack>
#include<string>
using namespace std;
// add bit by bit, with carry on; digits into stack, then to string
class Solution {
public:
string addBinary(string a, string b) {
stack<bool> ans;
bool carry = false;
int m = a.length()-1;
int n = b.length()-1;
while(m>=0&&n>=0) {
int tmp = a[m]-'0' +b[n]-'0' + carry; // formula
if(tmp >=2){
carry = true;
tmp= tmp -2;
}else{
carry = false;
}
ans.push(tmp==1);
m--;
n--;
}
// a is longer
while(m>=0) {
int tmp = a[m]-'0' + carry;
if(tmp >=2) {
carry = true;
tmp = tmp-2;
}else{
carry = false;
}
ans.push(tmp==1);
m--;
}
// b is longer
while(n>=0) {
int tmp = b[n]-'0' + carry;
if(tmp >=2) {
carry = true;
tmp = tmp -2;
}else{
carry = false;
}
ans.push(tmp==1);
n--;
}
// if carry on
if(carry)
ans.push(true);
// translate stack into string
int k = ans.size();
string result(k,'0');
for(int i = 0; i<k; i++) {
result[i]= ans.top()?'1':'0';
ans.pop();
}
return result;
}
};
int main() {
Solution slu;
cout<<slu.addBinary("11","11")<<endl;
}