Skip to content

Commit

Permalink
Merge pull request TheAlgorithms#1102 from shellhub/dev
Browse files Browse the repository at this point in the history
parseInteger
  • Loading branch information
yanglbme authored Oct 22, 2019
2 parents b0766bf + f1ad7a1 commit a60cb58
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions Maths/ParseInteger.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package Maths;

public class ParseInteger {
public static void main(String[] args) {
assert parseInt("123") == Integer.parseInt("123");
assert parseInt("-123") == Integer.parseInt("-123");
assert parseInt("0123") == Integer.parseInt("0123");
assert parseInt("+123") == Integer.parseInt("+123");
}

/**
* 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.
*/
public static int parseInt(String s) {
if (s == null) {
throw new NumberFormatException("null");
}
boolean isNegative = s.charAt(0) == '-';
boolean isPositive = s.charAt(0) == '+';
int number = 0;
for (int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); i < length; ++i) {
if (!Character.isDigit(s.charAt(i))) {
throw new NumberFormatException("s=" + s);
}
number = number * 10 + s.charAt(i) - '0';
}
return isNegative ? -number : number;
}
}

0 comments on commit a60cb58

Please sign in to comment.