Skip to content

Commit 9d86ed3

Browse files
committed
Time: 10 ms (13.02%), Space: 6.7 MB (30.34%) - LeetHub
1 parent 25ffd01 commit 9d86ed3

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

67-add-binary/67-add-binary.cpp

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public:
3+
int getValue(string& str, int pos) {
4+
if (str.size() > pos and pos >= 0) return str[pos] == '1' ? 1 : 0;
5+
else return 0;
6+
}
7+
8+
string toStr(int val) {
9+
return val == 1 ? "1": "0";
10+
}
11+
12+
string addBinary(string a, string b) {
13+
int Carry = 0;
14+
int n = max(a.size(), b.size());
15+
string c = "";
16+
17+
for(int i = 0; i < n; i++) {
18+
int sum = Carry + getValue(a, a.size()-i-1) + getValue(b, b.size()-i-1);
19+
int Digit = sum%2;
20+
Carry = (sum - Digit) / 2;
21+
c = toStr(Digit) + c;
22+
}
23+
if(Carry == 1) c = "1" + c;
24+
return c;
25+
}
26+
};

0 commit comments

Comments
 (0)