Back to LeetCode Series

LeetCode #8: String to Integer (atoi)

Convert a string to a 32-bit signed integer, handling whitespace, signs, and overflow — just like the real atoi function.

Difficulty: MediumPattern: String ParsingTime: 8 min read

The Problem

Implement a function that converts a string to a 32-bit signed integer, similar to the C/C++ atoi function.

  • Ignore leading whitespace
  • Check for optional + or - sign
  • Read digits until a non-digit or end of string
  • Clamp to [-2^31, 2^31 - 1] if overflow
  • If no valid number, return 0

Examples

Input: "42" → Output: 42  (Only digits → 42)

Input: " -42" → Output: -42  (Whitespace skipped, then negative sign)

Input: "4193 with words" → Output: 4193  (Reads 4193, stops at space/word)

Input: "words and 987" → Output: 0  (No valid number at start)

Input: "-91283472332" → Output: -2147483648  (Underflows 32-bit int → clamp to INT_MIN)

Input: "91283472332" → Output: 2147483647  (Overflows → clamp to INT_MAX)

Algorithm: Step-by-Step Parsing

  1. Trim leading spaces: Move pointer past whitespace
  2. Handle sign: Check for + or -, set sign flag
  3. Read digits: Loop while characters are digits ('0'–'9')
  4. Build number: num = num * 10 + digit
  5. Check overflow: Clamp before or after each step
  6. Return result: Apply sign and clamp

Simple Solution (Javascript)

js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
var myAtoi = function(s) {
  // Step 1: trim leading whitespace
  s = s.trim();
  if (!s) return 0;

  let i = 0, sign = 1, result = 0;
  const INT_MAX = 2 ** 31 - 1;
  const INT_MIN = -(2 ** 31);

  // Step 2: check sign
  if (s[i] === '+' || s[i] === '-') {
    sign = s[i] === '-' ? -1 : 1;
    i++;
  }

  // Step 3: read digits
  while (i < s.length && s[i] >= '0' && s[i] <= '9') {
    //result = result * 10 + (s[i].charCodeAt(0) - '0'.charCodeAt(0)); // charCodeAt converts character using ASCII to number
    
    let digit = parseInt(s[i]);
    result = result * 10 + digit;
    
    // Step 4: clamp if out of range
    if (sign * result <= INT_MIN) return INT_MIN;
    if (sign * result >= INT_MAX) return INT_MAX;

    i++;
  }

  return sign * result;
};

Solution (JavaScript)

js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
function myAtoi(s) {
  const INT_MAX = 2 ** 31 - 1;  // 2147483647
  const INT_MIN = -(2 ** 31);   // -2147483648

  let i = 0;
  let sign = 1;
  let result = 0;

  // Step 1: Skip whitespace
  while (i < s.length && s[i] === ' ') {
    i++;
  }

  // Step 2: Check sign
  if (i < s.length && (s[i] === '+' || s[i] === '-')) {
    sign = s[i] === '-' ? -1 : 1;
    i++;
  }

  // Step 3: Read digits
  while (i < s.length && /\d/.test(s[i])) {
    const digit = s[i].charCodeAt(0) - '0'.charCodeAt(0);

    // Check for overflow before multiplying
    if (result > Math.floor(INT_MAX / 10) || 
        (result === Math.floor(INT_MAX / 10) && digit > 7)) {
      return sign === 1 ? INT_MAX : INT_MIN;
    }

    result = result * 10 + digit;
    i++;
  }

  // Apply sign and clamp
  const final = result * sign;
  if (final > INT_MAX) return INT_MAX;
  if (final < INT_MIN) return INT_MIN;
  return final;
}

⚠️ Why Check Overflow Before Multiplying?

We can't do result * 10 + digit > INT_MAX because that operation might overflow JavaScript numbers or give incorrect results.

Instead, we check:

  • If result > INT_MAX / 10 → overflow
  • If result === INT_MAX / 10 and digit > 7 → overflow (since 2147483647)

🎮 Try It: Interactive atoi Parser

Type a string and watch how each character is processed — space, sign, digit, or stop.

atoi Visualizer

Step through parsing logic

600ms
-4193 with words
Status: Starting...
Sign: +
Current Number: 0
Step 1 / 10

🌍 Real-World Applications

Parsing strings into numbers is everywhere — and doing it safely is critical.

🔐 API Input Validation

When a JSON API receives "age": "25", it must parse it safely — ignoring spaces, clamping overflow, and rejecting invalid input.

🛡️ Security: Prevent Injection

Malicious inputs like " +---999abc" can crash systems if not handled. Robust parsing prevents denial-of-service attacks.

🧩 Compilers & Interpreters

When you write int x = 42;, the compiler parses "42" using logic nearly identical to this problem.

📱 Form Handling

User types " - 123 " in a form? Your parser should handle spaces and signs gracefully.

💡 Fun Fact: The real atoi() function in C returns 0 on error — which is also a valid number. That’s why modern code uses strtol() instead!

Summary

This problem teaches how to safely parse user input — a skill used in every API, form, and compiler. It’s not just about conversion — it’s about robustness, security, and edge-case thinking.

View All Challenges