forked from rost0413/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd_Binary.cpp
More file actions
105 lines (96 loc) · 2.37 KB
/
Add_Binary.cpp
File metadata and controls
105 lines (96 loc) · 2.37 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
Author: Weixian Zhou, ideazwx@gmail.com
Date: June 21, 2012
Problem: Add Binary
Difficulty: easy
Source: http://www.leetcode.com/onlinejudge
Notes:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
*/
#include <vector>
#include <set>
#include <climits>
#include <algorithm>
#include <iostream>
#include <cmath>
using namespace std;
class Solution {
public:
string addBinary(string a, string b) {
int i, j;
int carry;
int count;
string result;
i = a.length() - 1;
j = b.length() - 1;
carry = 0;
while (i >= 0 && j >= 0) {
count = 0;
if (carry == 1) count++;
if (a[i] == '1') count++;
if (b[j] == '1') count++;
if (count == 0) {
carry = 0;
result = "0" + result;
}
else if (count == 1) {
carry = 0;
result = "1" + result;
}
else if (count == 2) {
carry = 1;
result = "0" + result;
}
else {
carry = 1;
result = "1" + result;
}
i--;
j--;
}
while (i >= 0) {
count = 0;
if (a[i] == '1') count++;
if (carry == 1) count++;
if (count == 0) {
carry = 0;
result = "0" + result;
}
else if (count == 1) {
carry = 0;
result = "1" + result;
}
else{
carry = 1;
result = "0" + result;
}
i--;
}
while (j >= 0) {
count = 0;
if (b[j] == '1') count++;
if (carry == 1) count++;
if (count == 0) {
carry = 0;
result = "0" + result;
}
else if (count == 1) {
carry = 0;
result = "1" + result;
}
else{
carry = 1;
result = "0" + result;
}
j--;
}
if (carry) {
result = "1" + result;
}
return result;
}
};