File tree 1 file changed +12
-13
lines changed
scripts/algorithms/A/Add Binary
1 file changed +12
-13
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 1 ms (Top 100.0%) | Memory: 42.20 MB (Top 42.63%)
2
+
1
3
class Solution {
2
4
public String addBinary (String a , String b ) {
3
- StringBuilder sb = new StringBuilder ();
5
+ StringBuilder res = new StringBuilder ();
6
+ int i = a .length () - 1 ;
7
+ int j = b .length () - 1 ;
4
8
int carry = 0 ;
5
- int i = a .length () -1 ;
6
- int j = b .length () -1 ;
7
- while (i >=0 || j >=0 ){
9
+ while (i >= 0 || j >= 0 ){
8
10
int sum = carry ;
9
- if (i >=0 )
10
- sum +=a .charAt (i --)-'0' ; // -'0' is just to convert char in integer
11
- if (j >=0 )
12
- sum +=b .charAt (j --)-'0' ;
13
- sb .append (sum %2 ); // If we have sum = 1 1 then = 2 % 2 = 0 and 0 1 = 1 % 2 = 1
14
- carry = sum /2 ;
11
+ if (i >= 0 ) sum += a .charAt (i --) - '0' ;
12
+ if (j >= 0 ) sum += b .charAt (j --) - '0' ;
13
+ carry = sum > 1 ? 1 : 0 ;
14
+ res .append (sum % 2 );
15
15
}
16
- if (carry >0 )
17
- sb .append (carry );
18
- return sb .reverse ().toString ();
16
+ if (carry != 0 ) res .append (carry );
17
+ return res .reverse ().toString ();
19
18
}
20
19
}
You can’t perform that action at this time.
0 commit comments