1
1
package com .thealgorithms .maths ;
2
2
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
+
4
26
/**
5
27
* Parse a string to integer
6
28
*
@@ -9,18 +31,15 @@ public class ParseInteger {
9
31
* @throws NumberFormatException if the {@code string} does not contain a
10
32
* parsable integer.
11
33
*/
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 ) == '+' ;
18
39
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 ));
24
43
}
25
44
return isNegative ? -number : number ;
26
45
}
0 commit comments