We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 25ffd01 commit 9d86ed3Copy full SHA for 9d86ed3
67-add-binary/67-add-binary.cpp
@@ -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