Skip to content

Commit ecd709b

Browse files
committed
commit
1 parent cb466da commit ecd709b

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

67. Add Binary.java

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public String addBinary(String a, String b) {
3+
int carry = 0;
4+
int ai = a.length() - 1;
5+
int bi = b.length() - 1;
6+
7+
// sb is a variable to save the result
8+
StringBuilder sb = new StringBuilder();
9+
10+
while (ai >= 0 || bi >= 0 || carry == 1) {
11+
if (ai >= 0)
12+
carry += a.charAt(ai--) - '0';
13+
14+
if (bi >= 0)
15+
carry += b.charAt(bi--) - '0';
16+
17+
// Why mod 2 or div by 2, because this is in binary world
18+
// or base 2 number, not a decimal number or base 10 number
19+
sb.append(carry % 2);
20+
21+
carry /= 2;
22+
}
23+
24+
return sb.reverse().toString();
25+
}
26+
}

0 commit comments

Comments
 (0)