We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent cb466da commit ecd709bCopy full SHA for ecd709b
67. Add Binary.java
@@ -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