Bird
Raised Fist0
DSA Javaprogramming

String to Integer atoi in DSA Java

Choose your learning style10 modes available
Mental Model
Convert a string of characters into a number by reading each digit one by one and building the number step by step.
Analogy: Like reading a price tag digit by digit and writing down the total amount as you go, ignoring any extra words or symbols before or after the number.
"Input string: '  -42abc'\nRead chars -> skip spaces -> read sign -> read digits -> stop at non-digit\nNumber built: 0 -> 4 -> 42 -> apply sign -> -42"
Dry Run Walkthrough
Input: string: " -42abc"
Goal: Convert the string to the integer -42, ignoring spaces and stopping at first non-digit after digits
Step 1: Skip leading spaces
"-42abc"
Why: Spaces before the number do not affect the value, so we ignore them
Step 2: Read the sign '-' and record it as negative
"-42abc" with sign = -1
Why: The sign tells us if the number is positive or negative
Step 3: Read digit '4' and start building number: number = 4
number = 4
Why: Digits build the number from left to right
Step 4: Read digit '2' and update number: number = 4 * 10 + 2 = 42
number = 42
Why: Each new digit shifts the number left by one decimal place and adds the digit
Step 5: Encounter non-digit 'a', stop reading further
number = 42, sign = -1
Why: Non-digit means number parsing ends here
Step 6: Apply sign to number: result = -42
final number = -42
Why: Sign modifies the final number
Result:
final number = -42
Annotated Code
DSA Java
public class AtoiConverter {
    public static int myAtoi(String s) {
        int i = 0, n = s.length();
        while (i < n && s.charAt(i) == ' ') i++; // skip spaces
        int sign = 1;
        if (i < n && (s.charAt(i) == '+' || s.charAt(i) == '-')) {
            sign = (s.charAt(i) == '-') ? -1 : 1;
            i++;
        }
        int number = 0;
        while (i < n && Character.isDigit(s.charAt(i))) {
            int digit = s.charAt(i) - '0';
            // Check overflow
            if (number > (Integer.MAX_VALUE - digit) / 10) {
                return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            number = number * 10 + digit;
            i++;
        }
        return number * sign;
    }

    public static void main(String[] args) {
        String input = "  -42abc";
        int result = myAtoi(input);
        System.out.println(result);
    }
}
while (i < n && s.charAt(i) == ' ') i++; // skip spaces
skip all leading spaces to find start of number
if (i < n && (s.charAt(i) == '+' || s.charAt(i) == '-')) { sign = (s.charAt(i) == '-') ? -1 : 1; i++; }
detect and record sign if present
while (i < n && Character.isDigit(s.charAt(i))) {
read digits one by one to build number
if (number > (Integer.MAX_VALUE - digit) / 10) { return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; }
check for overflow and clamp to integer limits
number = number * 10 + digit;
append digit to current number
return number * sign;
apply sign and return final integer
OutputSuccess
-42
Complexity Analysis
Time: O(n) because we scan the string once from left to right
Space: O(1) because we use only a few variables regardless of input size
vs Alternative: Compared to parsing with built-in functions that may throw exceptions, this method safely handles invalid input and stops early, avoiding extra overhead
Edge Cases
empty string
returns 0 because no digits found
DSA Java
while (i < n && s.charAt(i) == ' ') i++;
string with only spaces
returns 0 after skipping all spaces
DSA Java
while (i < n && s.charAt(i) == ' ') i++;
string with number exceeding integer max
returns Integer.MAX_VALUE or Integer.MIN_VALUE depending on sign
DSA Java
if (number > (Integer.MAX_VALUE - digit) / 10) { return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; }
string with no digits after sign
returns 0 because no digits found
DSA Java
while (i < n && Character.isDigit(s.charAt(i)))
When to Use This Pattern
When you see a problem asking to convert a string to a number with rules about spaces, signs, and invalid characters, use the 'String to Integer atoi' pattern to parse carefully and handle edge cases.
Common Mistakes
Mistake: Not skipping leading spaces before parsing number
Fix: Add a loop to skip all spaces before reading sign or digits
Mistake: Not handling overflow and causing wrong results or errors
Fix: Check before adding a digit if number will overflow and clamp accordingly
Mistake: Parsing characters after non-digit without stopping
Fix: Stop parsing as soon as a non-digit character is encountered after digits
Summary
Converts a string to an integer by reading characters step by step, handling spaces, signs, digits, and stopping at invalid characters.
Use when you need to safely parse numbers from strings that may contain extra spaces, signs, or invalid trailing characters.
The key insight is to read characters carefully in order: skip spaces, detect sign, build number digit by digit, and stop at the first invalid character.

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