00:00

Problem Statement

Input/Output Examples

Visual Explanation

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.

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.

Complexity Analysis

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. int goes from -2147483648 to 2147483647, so negating the most negative value overflows.
  • Check overflow before multiplying. After result * 10 has 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.