forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 39
/
addBinary.cpp
52 lines (45 loc) · 1.18 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
// Source : https://oj.leetcode.com/problems/add-binary/
// Author : Hao Chen
// Date : 2014-07-05
/**********************************************************************************
*
* Given two binary strings, return their sum (also a binary string).
*
* For example,
* a = "11"
* b = "1"
* Return "100".
*
*
**********************************************************************************/
#include <iostream>
#include <string>
using namespace std;
string addBinary(string a, string b) {
int alen = a.size();
int blen = b.size();
bool carry = false;
string result;
while( alen>0 || blen>0) {
int abit = alen<=0 ? 0 : a[alen-1]-'0';
int bbit = blen<=0 ? 0 : b[blen-1]-'0';
int cbit = carry ? 1 : 0;
result.insert(result.begin(), '0' + ((abit+bbit+cbit) & 1) );
carry = (abit+bbit+cbit>1);
alen--; blen--;
}
if (carry){
result.insert(result.begin(), '1');
}
return result;
}
int main(int argc, char** argv)
{
string a = "11";
string b = "1";
if (argc>2){
a = argv[1];
b = argv[2];
}
cout << a << "+" << b << "=" << addBinary(a, b) << endl;
}