Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 21.3k
Expand file tree
/
Copy pathParseInteger.java
More file actions
Latest commit
46 lines (40 loc) · 1.43 KB
/
Copy pathParseInteger.java
File metadata and controls
46 lines (40 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
packagecom.thealgorithms.maths;
publicfinalclassParseInteger {
privateParseInteger() {
}
privatestaticvoidcheckInput(finalStrings) {
if (s == null) {
thrownewNumberFormatException("Input parameter must not be null!");
}
if (s.isEmpty()) {
thrownewNumberFormatException("Input parameter must not be empty!");
}
}
privatestaticvoidcheckDigitAt(finalStrings, finalintpos) {
if (!Character.isDigit(s.charAt(pos))) {
thrownewNumberFormatException("Input parameter of incorrect format: " + s);
}
}
privatestaticintdigitToInt(finalchardigit) {
returndigit - '0';
}
/**
* Parse a string to integer
*
* @param s the string
* @return the integer value represented by the argument in decimal.
* @throws NumberFormatException if the {@code string} does not contain a
* parsable integer.
*/
publicstaticintparseInt(finalStrings) {
checkInput(s);
finalbooleanisNegative = s.charAt(0) == '-';
finalbooleanisPositive = s.charAt(0) == '+';
intnumber = 0;
for (inti = isNegative || isPositive ? 1 : 0, length = s.length(); i < length; ++i) {
checkDigitAt(s, i);
number = number * 10 + digitToInt(s.charAt(i));
}
returnisNegative ? -number : number;
}
}