File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ public class Solution {
2
+ public String addBinary (String a , String b ) {
3
+ StringBuilder sb = new StringBuilder ();
4
+ int i = a .length (), j = b .length ();
5
+ boolean carry = false ;
6
+
7
+ while (i > 0 || j > 0 || carry ) {
8
+ char f = --i < 0 ? '0' : a .charAt (i );
9
+ char s = --j < 0 ? '0' : b .charAt (j );
10
+
11
+ if (f == '1' && s == '1' ) {
12
+ if (carry == true ) {
13
+ sb .insert (0 , '1' );
14
+ } else {
15
+ sb .insert (0 , '0' );
16
+ carry = true ;
17
+ }
18
+ } else if (f == '0' && s == '0' ) {
19
+ if (carry == true ) {
20
+ sb .insert (0 , '1' );
21
+ carry = false ;
22
+ } else {
23
+ sb .insert (0 , '0' );
24
+ }
25
+ } else {
26
+ if (carry == true ) {
27
+ sb .insert (0 , '0' );
28
+ } else {
29
+ sb .insert (0 , '1' );
30
+ }
31
+ }
32
+ }
33
+ return sb .toString ();
34
+ }
35
+ }
You can’t perform that action at this time.
0 commit comments