GeezerVison is showing github.com — Merge pull request #1102 from shellhub/dev · pythonpeixun/Java@a60cb58
File tree
Expand file treeCollapse file tree
Open diff view settings
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboard +33Lines changed: 33 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
|
| 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 | +} |