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.
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
- Trim leading spaces: Move pointer past whitespace
- Handle sign: Check for
+
or-
, set sign flag - Read digits: Loop while characters are digits (
'0'–'9'
) - Build number:
num = num * 10 + digit
- Check overflow: Clamp before or after each step
- Return result: Apply sign and clamp
Simple Solution (Javascript)
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)
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
anddigit > 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
🌍 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.