Java String Program · S25
Convert a String to an Integer Without parseInt() in Java
Turn "-2048" into the number -2048 one digit at a time. The real test is rejecting bad input and catching overflow, including the Integer.MIN_VALUE corner case.
Problem Statement
Write a method that converts a string to an int without calling Integer.parseInt() or Integer.valueOf(). The string may start with + or -, followed by one or more digits.
Any other character, an empty string, a lone sign, or a value outside the int range must throw a NumberFormatException, just as parseInt() would.
Input/Output Examples
"-2048"Output-2048Explanation: the sign is read first, then the digits 2, 0, 4 and 8."-2147483648"Output-2147483648Explanation: Integer.MIN_VALUE is valid even though 2147483648 is not."2147483648" and "12a"OutputerrorExplanation: the first is one more than Integer.MAX_VALUE; the second contains a letter.Visual Explanation
"-2048": after the sign, each digit shifts the value one place left and is added (here subtracted, because the value is built as a negative number).c - '0' turns a digit character into its value, and result * 10 makes room for it. Building the value as a negative number is the trick the JDK uses, because the negative range of int is one larger than the positive range.
Approaches
Both approaches accept exactly what Integer.parseInt() accepts. They differ in how they detect overflow.
Approach 1: Negative Accumulation (Recommended)
Idea: build the value as a negative number and compare it with a negative limit before each step, so even Integer.MIN_VALUE fits.
- Read an optional sign and reject a lone sign or an empty string.
- Set
limittoInteger.MIN_VALUEfor negatives and-Integer.MAX_VALUEotherwise. - For each digit, check that
result * 10 - digitstays at or abovelimit, then apply it. - Return
resultfor negatives and-resultfor positives.
Time: O(n) · Space: O(1).
Approach 2: long Accumulator
Idea: build the magnitude in a long and stop as soon as it exceeds the allowed maximum for the sign.
- Read the optional sign.
- Set
maxto2147483648for negatives and2147483647otherwise. - Add each digit with
value * 10 + digit, throwing as soon asvalue > max. - Apply the sign and cast to
int.
Time: O(n) · Space: O(1).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Negative Accumulation (Recommended)
Both checks happen before the arithmetic, so the int never overflows, and no long is needed.
public class ParseIntNegative {
// Builds the value as a negative number, as Integer.parseInt() does,
// so that -2147483648 fits even though 2147483648 does not
static int toInt(String s) {
if (s.isEmpty()) {
throw new NumberFormatException("empty string");
}
int i = 0;
boolean negative = false;
char first = s.charAt(0);
if (first == '-' || first == '+') {
negative = first == '-';
i = 1;
if (s.length() == 1) {
throw new NumberFormatException("no digits");
}
}
int limit = negative ? Integer.MIN_VALUE : -Integer.MAX_VALUE;
int limitBeforeMultiply = limit / 10;
int result = 0;
for (; i < s.length(); i++) {
char c = s.charAt(i);
if (c < '0' || c > '9') {
throw new NumberFormatException("invalid character '" + c + "'");
}
int digit = c - '0';
if (result < limitBeforeMultiply) {
throw new NumberFormatException("out of int range");
}
result *= 10;
if (result < limit + digit) {
throw new NumberFormatException("out of int range");
}
result -= digit;
}
return negative ? result : -result;
}
public static void main(String[] args) {
String[] inputs = {"-2048", "+75", "0042", "-2147483648", "2147483648", "12a", "-"};
for (String s : inputs) {
try {
System.out.println("\"" + s + "\" -> " + toInt(s));
} catch (NumberFormatException e) {
System.out.println("\"" + s + "\" -> error: " + e.getMessage());
}
}
}
}
"-2048" -> -2048 "+75" -> 75 "0042" -> 42 "-2147483648" -> -2147483648 "2147483648" -> error: out of int range "12a" -> error: invalid character 'a' "-" -> error: no digits
Time complexity: O(n) · Space complexity: O(1).
Approach 2: long Accumulator
Easier to read. Checking inside the loop also prevents the long itself from overflowing on very long inputs.
public class ParseIntLong {
// Accumulates the magnitude in a long and checks the range at every step
static int toInt(String s) {
if (s.isEmpty()) {
throw new NumberFormatException("empty string");
}
int i = 0;
boolean negative = false;
char first = s.charAt(0);
if (first == '-' || first == '+') {
negative = first == '-';
i = 1;
if (s.length() == 1) {
throw new NumberFormatException("no digits");
}
}
long max = negative ? 2147483648L : Integer.MAX_VALUE;
long value = 0;
for (; i < s.length(); i++) {
char c = s.charAt(i);
if (c < '0' || c > '9') {
throw new NumberFormatException("invalid character '" + c + "'");
}
value = value * 10 + (c - '0');
if (value > max) {
throw new NumberFormatException("out of int range"); // stops before long can overflow
}
}
return (int) (negative ? -value : value);
}
public static void main(String[] args) {
String[] inputs = {"-2048", "+75", "0042", "-2147483648", "2147483648", "12a", "-"};
for (String s : inputs) {
try {
System.out.println("\"" + s + "\" -> " + toInt(s));
} catch (NumberFormatException e) {
System.out.println("\"" + s + "\" -> error: " + e.getMessage());
}
}
}
}
"-2048" -> -2048 "+75" -> 75 "0042" -> 42 "-2147483648" -> -2147483648 "2147483648" -> error: out of int range "12a" -> error: invalid character 'a' "-" -> error: no digits
Time complexity: O(n) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Negative Accumulation | O(n) | O(1) |
| long Accumulator | O(n) | O(1) |
Here n is the length of the string. Each character is examined once and only a few variables are used.
Interview Tips and Recommended Approach
- Explain the asymmetric range.
intgoes from-2147483648to2147483647, so negating the most negative value overflows. - Check overflow before multiplying. After
result * 10has overflowed, the value is already wrong and cannot be checked. - List the invalid cases: empty string, lone
+or-, any non-digit, and out-of-range values. - Clarify the variant. Some versions skip leading spaces, ignore trailing text or clamp to the limits instead of throwing; ask before coding.
Recommended Approach: Negative Accumulation
Why: it handles the full int range, including Integer.MIN_VALUE, using only int arithmetic, and it is the same technique the JDK's own parseInt() uses.