11package com .thealgorithms .maths ;
22
3- public class ParseInteger {
3+ public final class ParseInteger {
4+ private ParseInteger () {
5+ }
6+
7+ private static void checkInput (final String s ) {
8+ if (s == null ) {
9+ throw new NumberFormatException ("Input parameter must not be null!" );
10+ }
11+ if (s .isEmpty ()) {
12+ throw new NumberFormatException ("Input parameter must not be empty!" );
13+ }
14+ }
15+
16+ private static void checkDigitAt (final String s , final int pos ) {
17+ if (!Character .isDigit (s .charAt (pos ))) {
18+ throw new NumberFormatException ("Input parameter of incorrect format: " + s );
19+ }
20+ }
21+
22+ private static int digitToInt (final char digit ) {
23+ return digit - '0' ;
24+ }
25+
426 /**
527 * Parse a string to integer
628 *
@@ -9,18 +31,15 @@ public class ParseInteger {
931 * @throws NumberFormatException if the {@code string} does not contain a
1032 * parsable integer.
1133 */
12- public static int parseInt (String s ) {
13- if (s == null || s .length () == 0 ) {
14- throw new NumberFormatException ("Input parameter must not be null!" );
15- }
16- boolean isNegative = s .charAt (0 ) == '-' ;
17- boolean isPositive = s .charAt (0 ) == '+' ;
34+ public static int parseInt (final String s ) {
35+ checkInput (s );
36+
37+ final boolean isNegative = s .charAt (0 ) == '-' ;
38+ final boolean isPositive = s .charAt (0 ) == '+' ;
1839 int number = 0 ;
19- for (int i = isNegative ? 1 : isPositive ? 1 : 0 , length = s .length (); i < length ; ++i ) {
20- if (!Character .isDigit (s .charAt (i ))) {
21- throw new NumberFormatException ("Input parameter of incorrect format: " + s );
22- }
23- number = number * 10 + s .charAt (i ) - '0' ;
40+ for (int i = isNegative || isPositive ? 1 : 0 , length = s .length (); i < length ; ++i ) {
41+ checkDigitAt (s , i );
42+ number = number * 10 + digitToInt (s .charAt (i ));
2443 }
2544 return isNegative ? -number : number ;
2645 }
0 commit comments