Bird
Raised Fist0
DSA Javaprogramming~10 mins

String to Integer atoi in DSA Java - Execution Trace

Choose your learning style10 modes available
Concept Flow - String to Integer atoi
Step 1: Skip spaces
i=0,1 → spaces skipped → i=2
↓
Step 2: Read sign
char='-' → sign=-1 → i=3
↓
Step 3: Read digits
i=3: '4' → result=4
↓
Step 4: Apply sign + clamp
-1 Ɨ 42 = -42 (in range)
atoi processes the string in exactly four sequential steps: skip leading whitespace, detect optional sign, accumulate digits left-to-right, then apply sign and clamp to 32-bit integer bounds. The key insight is stopping immediately on any non-digit character and clamping overflow before it occurs.
Execution Sample
DSA Java
public int myAtoi(String s) {
    int i = 0, n = s.length();
    // Step 1: skip whitespace
    while (i < n && s.charAt(i) == ' ') i++;
    // Step 2: read sign
    int sign = 1;
    if (i < n && (s.charAt(i) == '+' || s.charAt(i) == '-')) {
        sign = (s.charAt(i) == '-') ? -1 : 1;
        i++;
    }
    // Step 3: accumulate digits
    int result = 0;
    while (i < n && Character.isDigit(s.charAt(i))) {
        int digit = s.charAt(i) - '0';
        // Step 4: overflow check before multiplying
        if (result > (Integer.MAX_VALUE - digit) / 10) {
            return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
        }
        result = result * 10 + digit;
        i++;
    }
    return sign * result;
}
Trace input ' -42abc': i advances past 2 spaces (i=2), reads '-' setting sign=-1 (i=3), reads '4' building result=4 (i=4), reads '2' building result=42 (i=5), hits 'a' which is non-digit so loop exits. Returns -1 Ɨ 42 = -42.
Execution Table
icharactionsignresult
0' 'skip space10
1' 'skip space10
2'-'set sign=-1, i++-10
3'4'digit: result=0*10+4-14
4'2'digit: result=4*10+2-142
5'a'non-digit: STOP-142
--return -1Ɨ42-1-42
šŸ’” Loop exits at i=5 because 'a' fails Character.isDigit(). Final return applies sign: -1 Ɨ 42 = -42.
Variable Tracker
stepisignresultdigitoverflow?
init010-no
skip spaces210-no
read sign3-10-no
read '4'4-144no
read '2'5-1422no
stop at 'a'5-142-no
return--1-42-no
Key Moments - 4 Insights
Why must overflow be checked BEFORE computing result = result * 10 + digit?
result * 10 can itself overflow int range before adding digit. Checking result > (MAX_VALUE - digit) / 10 detects this without performing the overflowing multiplication.
What happens if the input is '+-12'?
The sign block reads '+' and advances i. The next character '-' is not a digit so the digit loop never executes. The function returns sign * 0 = 0.
Why use Character.isDigit() instead of checking c >= '0' && c <= '9'?
Both work for ASCII digits in this problem. Character.isDigit() is more readable and idiomatic Java. Both stop correctly on letters, spaces, or special characters.
Why is the overflow clamp split between MAX_VALUE and MIN_VALUE based on sign?
Integer.MAX_VALUE is 2147483647 and Integer.MIN_VALUE is -2147483648. They differ by 1 in absolute value. Applying sign after clamping ensures 'āˆ’2147483648' returns MIN_VALUE correctly rather than MAX_VALUE.
Visual Quiz - 4 Questions
Test your understanding
For input ' +0 123', what does myAtoi return?
A123
B0
C0123
D-1
šŸ’” Hint
The digit loop stops at the first non-digit character after reading '0'.
For input '2147483648' (MAX_VALUE + 1), what does myAtoi return?
A-2147483648
B2147483648
C2147483647
D0
šŸ’” Hint
The overflow check fires before the result exceeds MAX_VALUE and clamps to Integer.MAX_VALUE.
At which step does the algorithm stop processing '42xyz99'?
AAfter reading all characters including 99
BAfter reading '42', stops at 'x'
CAfter reading '42xyz', stops at '9'
DAfter reading '42xyz99'
šŸ’” Hint
The digit loop exits immediately on the first non-digit character — it does not skip non-digits and resume.
What does myAtoi return for input '-91283472332' (below MIN_VALUE)?
A-91283472332
B0
C-2147483647
D-2147483648
šŸ’” Hint
Negative overflow clamps to Integer.MIN_VALUE = -2147483648.
Concept Snapshot
atoi = 4 sequential steps: (1) skip spaces, (2) read optional sign, (3) accumulate digits stopping on first non-digit, (4) clamp to 32-bit range. Overflow must be detected before multiplication, not after. The algorithm never backtracks — one left-to-right pass only.
Full Transcript
Let's trace String to Integer atoi step by step on input ' -42abc'. We start with index i=0. The first two characters are spaces, so we advance i to 2. Now i=2 and we see '-'. This is a sign character so we set sign to -1 and advance to i=3. Now we enter the digit loop. At i=3 we have '4'. digit = '4' - '0' = 4. Overflow check: is 0 > (2147483647 - 4) / 10? That's 0 > 214748364, which is false. So result = 0 * 10 + 4 = 4. Advance to i=4. At i=4 we have '2'. digit = 2. Overflow check: is 4 > (2147483647 - 2) / 10 = 214748364? No. result = 4 * 10 + 2 = 42. Advance to i=5. At i=5 we have 'a'. Character.isDigit('a') is false. The loop exits immediately. We return sign * result = -1 * 42 = -42. The key discipline: stop on the first non-digit, never resume. And always check overflow before multiplying, not after.

Practice

(1/5)
1. What does the atoi function do when given a string input?
easy
A. Counts the number of characters in the string
B. Converts the string to a floating-point number
C. Reverses the string characters
D. Converts the string to an integer number

Solution

  1. Step 1: Understand the purpose of atoi

    The atoi function stands for ASCII to integer and converts a string representing a number into an integer value.
  2. Step 2: Compare options with function behavior

    Only Converts the string to an integer number matches the behavior of converting string to integer. Other options describe different operations.
  3. Final Answer:

    Converts the string to an integer number -> Option D
  4. Quick Check:

    atoi converts string to integer [OK]
Hint: Remember atoi means ASCII to integer conversion [OK]
Common Mistakes:
  • Thinking atoi converts to float
  • Confusing atoi with string length functions
  • Assuming it reverses the string
2. Which of the following Java code snippets correctly converts a string s to an integer using Integer.parseInt?
easy
A. int num = parseInt.Integer(s);
B. int num = Integer.parseInt(s);
C. int num = Integer.valueOf(s).toInt();
D. int num = Integer.toString(s);

Solution

  1. Step 1: Identify correct method syntax

    Java's correct method to convert string to int is Integer.parseInt(string).
  2. Step 2: Check each option

    int num = Integer.parseInt(s); uses correct syntax. int num = Integer.toString(s); tries to convert int to string incorrectly. int num = Integer.valueOf(s).toInt(); uses invalid method chaining. int num = parseInt.Integer(s); has wrong method call order.
  3. Final Answer:

    int num = Integer.parseInt(s); -> Option B
  4. Quick Check:

    Correct Java syntax is Integer.parseInt(s) [OK]
Hint: Use Integer.parseInt(string) to convert string to int [OK]
Common Mistakes:
  • Using Integer.toString instead of parseInt
  • Incorrect method chaining like valueOf().toInt()
  • Wrong method call order
3. What will be the output of the following Java code?
String s = "  -42abc";
int result = 0;
int i = 0;
boolean negative = false;

// Skip leading spaces
while (i < s.length() && s.charAt(i) == ' ') i++;

// Check sign
if (i < s.length() && (s.charAt(i) == '-' || s.charAt(i) == '+')) {
    negative = s.charAt(i) == '-';
    i++;
}

// Convert digits
while (i < s.length() && Character.isDigit(s.charAt(i))) {
    result = result * 10 + (s.charAt(i) - '0');
    i++;
}

if (negative) result = -result;
System.out.println(result);
medium
A. -42
B. 42
C. 0
D. NumberFormatException

Solution

  1. Step 1: Skip spaces and detect sign

    The code skips leading spaces, finds '-', sets negative true, and moves index forward.
  2. Step 2: Parse digits until non-digit

    It reads '4' and '2', converts to integer 42, stops at 'a'. Then applies negative sign.
  3. Final Answer:

    -42 -> Option A
  4. Quick Check:

    Parsed number with sign is -42 [OK]
Hint: Skip spaces, check sign, parse digits until non-digit [OK]
Common Mistakes:
  • Not skipping spaces before parsing
  • Ignoring sign character
  • Parsing non-digit characters causing errors
4. The following code attempts to convert a string to integer but throws an exception. What is the main error?
String s = "123abc";
int num = Integer.parseInt(s);
System.out.println(num);
medium
A. parseInt method does not exist in Integer class
B. Missing import for Integer class
C. String contains non-digit characters causing NumberFormatException
D. Variable num is not declared

Solution

  1. Step 1: Understand Integer.parseInt behavior

    Integer.parseInt expects a string with only digits (and optional sign). Non-digit characters cause NumberFormatException.
  2. Step 2: Analyze input string

    String "123abc" contains letters after digits, causing the exception.
  3. Final Answer:

    String contains non-digit characters causing NumberFormatException -> Option C
  4. Quick Check:

    Non-digit chars cause NumberFormatException [OK]
Hint: parseInt fails if string has letters or symbols [OK]
Common Mistakes:
  • Assuming parseInt ignores trailing letters
  • Forgetting to handle exceptions
  • Thinking parseInt needs imports
5. You want to implement a custom atoi function in Java that handles leading spaces, optional '+' or '-' sign, digits, and stops parsing at the first non-digit character. Which approach below correctly handles integer overflow during conversion?
hard
A. Use a long variable to accumulate and check if it exceeds Integer.MAX_VALUE or Integer.MIN_VALUE before casting
B. Ignore overflow and cast directly to int after parsing all digits
C. Use Integer.parseInt inside a try-catch block to catch overflow exceptions
D. Stop parsing digits once the number of digits exceeds 10

Solution

  1. Step 1: Understand overflow risk in atoi

    Parsing digits can exceed int limits, causing incorrect results or errors.
  2. Step 2: Use long to detect overflow before casting

    Accumulating in a long lets you check if value goes beyond int range, then clamp or handle accordingly.
  3. Step 3: Evaluate other options

    Ignore overflow and cast directly to int after parsing all digits ignores overflow, causing wrong results. Use Integer.parseInt inside a try-catch block to catch overflow exceptions is invalid because parseInt throws NumberFormatException, not overflow exception. Stop parsing digits once the number of digits exceeds 10 is unreliable as digit count alone doesn't guarantee overflow.
  4. Final Answer:

    Use a long variable to accumulate and check if it exceeds Integer.MAX_VALUE or Integer.MIN_VALUE before casting -> Option A
  5. Quick Check:

    Use long to detect overflow before int cast [OK]
Hint: Use long to detect overflow before converting to int [OK]
Common Mistakes:
  • Ignoring overflow and casting directly
  • Relying on digit count only
  • Misusing try-catch for overflow
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard