Skip to content

Commit f1ad7a1

Browse files
parseInteger
1 parent b0766bf commit f1ad7a1

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Maths/ParseInteger.java

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package Maths;
2+
3+
public class ParseInteger {
4+
public static void main(String[] args) {
5+
assert parseInt("123") == Integer.parseInt("123");
6+
assert parseInt("-123") == Integer.parseInt("-123");
7+
assert parseInt("0123") == Integer.parseInt("0123");
8+
assert parseInt("+123") == Integer.parseInt("+123");
9+
}
10+
11+
/**
12+
* Parse a string to integer
13+
*
14+
* @param s the string
15+
* @return the integer value represented by the argument in decimal.
16+
* @throws NumberFormatException if the {@code string} does not contain a parsable integer.
17+
*/
18+
public static int parseInt(String s) {
19+
if (s == null) {
20+
throw new NumberFormatException("null");
21+
}
22+
boolean isNegative = s.charAt(0) == '-';
23+
boolean isPositive = s.charAt(0) == '+';
24+
int number = 0;
25+
for (int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); i < length; ++i) {
26+
if (!Character.isDigit(s.charAt(i))) {
27+
throw new NumberFormatException("s=" + s);
28+
}
29+
number = number * 10 + s.charAt(i) - '0';
30+
}
31+
return isNegative ? -number : number;
32+
}
33+
}

0 commit comments

Comments
 (0)