String to Integer (atoi)

Medium StringMath

Problem

Implement atoi: skip leading whitespace, parse optional sign and as many digits as possible, clamp to 32-bit int range.

Example 1 Input: "42" Output: 42
Example 2 Input: " -42" Output: -42
Example 3 Input: "4193 with words" Output: 4193
Example 4 Input: "words and 987" Output: 0
Example 5 Input: "-91283472332" Output: -2147483648

Constraints

Approach — Core Patterns

This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: see the walkthrough below.

Solution code

Python

class Solution:
    def myAtoi(self, s):
        s = s.lstrip()
        if not s:
            return 0
        i = 0
        sign = 1
        if s[0] in '+-':
            sign = -1 if s[0] == '-' else 1
            i = 1
        num = 0
        while i < len(s) and s[i].isdigit():
            num = num * 10 + int(s[i])
            i += 1
        num *= sign
        return max(-2**31, min(2**31 - 1, num))

Java

class Solution {
    public int myAtoi(String s) {
        int i = 0, n = s.length();
        while (i < n && s.charAt(i) == ' ') i++;
        if (i == n) return 0;
        int sign = 1;
        if (s.charAt(i) == '+' || s.charAt(i) == '-') sign = s.charAt(i++) == '-' ? -1 : 1;
        int result = 0;
        while (i < n && Character.isDigit(s.charAt(i))) {
            int d = s.charAt(i++) - '0';
            if (result > (Integer.MAX_VALUE - d) / 10) {
                return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            result = result * 10 + d;
        }
        return sign * result;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve String to Integer (atoi) interactively → ← All solutions