File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public String addBinary (String a , String b ) {
3
+ // Go from right to left
4
+ int len1 = a .length ();
5
+ int len2 = b .length ();
6
+
7
+ int minLen = Math .min (len1 , len2 );
8
+ int maxLen = Math .max (len1 , len2 );
9
+
10
+ int index1 = len1 - 1 ;
11
+ int index2 = len2 - 1 ;
12
+
13
+ StringBuilder bld = new StringBuilder ();
14
+ boolean carry = false ;
15
+
16
+ while ((index1 >= 0 ) || (index2 >= 0 ) || carry ) {
17
+ char c1 = (index1 >= 0 ) ? a .charAt (index1 ) : '0' ;
18
+ char c2 = (index2 >= 0 ) ? b .charAt (index2 ) : '0' ;
19
+
20
+ char sum ;
21
+ if ((c1 == '0' ) && (c2 == '0' )) { // Both zeros
22
+ sum = carry ? '1' : '0' ;
23
+ carry = false ;
24
+ }
25
+ else if ((c1 == '1' ) && (c2 == '1' )) { // Both ones
26
+ sum = carry ? '1' : '0' ;
27
+ carry = true ;
28
+ }
29
+ else { // Any one with a one
30
+ sum = carry ? '0' : '1' ;
31
+ // carry will be forwarded
32
+ }
33
+ bld .append (sum );
34
+
35
+ index1 --;
36
+ index2 --;
37
+ }
38
+
39
+ return bld .reverse ().toString ();
40
+ }
41
+ }
You can’t perform that action at this time.
0 commit comments