Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit f1ad7a1

Browse filesBrowse files
parseInteger
1 parent b0766bf commit f1ad7a1
Copy full SHA for f1ad7a1

1 file changed

+33Lines changed: 33 additions & 0 deletions

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎Maths/ParseInteger.java‎

Copy file name to clipboard
+33Lines changed: 33 additions & 0 deletions
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 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.