File tree Expand file tree Collapse file tree 1 file changed +13
-12
lines changed Expand file tree Collapse file tree 1 file changed +13
-12
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public String addBinary (String a , String b ) {
3
- int carry = 0 ;
4
3
StringBuilder sb = new StringBuilder ();
5
- int idxA = a .length () - 1 ;
6
- int idxB = b .length () - 1 ;
7
- while (idxA >= 0 || idxB >= 0 || carry > 0 ) {
8
- int temp = (
9
- (idxA >= 0 ? Character .getNumericValue (a .charAt (idxA --)) : 0 ) +
10
- (idxB >= 0 ? Character .getNumericValue (b .charAt (idxB --)) : 0 ) +
11
- carry
12
- );
13
- carry = temp > 1 ? 1 : 0 ;
14
- temp = temp > 1 ? (temp == 2 ? 0 : 1 ) : temp ;
15
- sb .append (temp );
4
+ int endIdxA = a .length () - 1 ;
5
+ int endIdxB = b .length () - 1 ;
6
+ int carry = 0 ;
7
+ while (endIdxA >= 0 || endIdxB >= 0 || carry > 0 ) {
8
+ int value = carry ;
9
+ if (endIdxA >= 0 ) {
10
+ value += Character .getNumericValue (a .charAt (endIdxA --));
11
+ }
12
+ if (endIdxB >= 0 ) {
13
+ value += Character .getNumericValue (b .charAt (endIdxB --));
14
+ }
15
+ sb .append (value % 2 );
16
+ carry = value / 2 ;
16
17
}
17
18
return sb .reverse ().toString ();
18
19
}
You can’t perform that action at this time.
0 commit comments