-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddBinary.cpp
More file actions
executable file
·44 lines (40 loc) · 944 Bytes
/
AddBinary.cpp
File metadata and controls
executable file
·44 lines (40 loc) · 944 Bytes
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
//
// AddBinary.cpp
// leetcode
//
// Created by witwolf on 5/8/15.
// Copyright (c) 2015 witwolf. All rights reserved.
//
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class Solution {
public:
string addBinary(string a, string b) {
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
auto length = max(a.length(),b.length());
a.append(length-a.length(),'0');
b.append(length-b.length(),'0');
char base = 0;
for(auto k = 0 ; k < length ; ++k){
base += a[k] + b[k] - 2 * '0';
a[k] = base % 2 + '0';
base = base / 2;
}
if(base){
a.push_back('1');
}
reverse(a.begin(), a.end());
return a;
}
};
int main(int argc,char **argv){
string a,b;
Solution s;
while(true){
cin >> a >> b;
cout << s.addBinary(a, b) << endl;
}
}