Skip to content

Commit 4f2ec37

Browse files
committed
basic addition
1 parent 96f4e56 commit 4f2ec37

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

Two Pointers/addBinary.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
public String addBinary(String a, String b) {
3+
/*
4+
Starting from the last bit, snd appending the result to string and noting the carry
5+
*/
6+
StringBuilder sb = new StringBuilder();
7+
int i = a.length() - 1;
8+
int j = b.length() - 1;
9+
int carry = 0;
10+
11+
while(i>=0 || j>= 0) {
12+
int sum = carry;
13+
if (j>=0) {
14+
sum = sum + b.charAt(j) - '0'; // '1' - '0' = 1
15+
// System.out.println(sum);
16+
j--;
17+
}
18+
19+
if (i >= 0) {
20+
sum = sum + a.charAt(i) - '0';
21+
// System.out.println(sum);
22+
i--;
23+
}
24+
sb.append(sum % 2);
25+
26+
carry = sum/2;
27+
// System.out.println("carry " + carry);
28+
}
29+
30+
if (carry != 0) {
31+
sb.append(carry);
32+
}
33+
34+
return sb.reverse().toString();
35+
}
36+
}

0 commit comments

Comments
 (0)