← Back to Leo Academy Masterclass

Problem #8: String to Integer (atoi)

Medium Array & String

Intuition & Strategy Breakdown

Discard leading whitespace, determine sign from the next character, then convert consecutive digits into an integer while clamping the result within 32-bit signed integer limits.

Python Solution

class Solution:
    def myAtoi(self, s: str) -> int:
        s = s.strip()
        if not s:
            return 0
        sign = 1
        i = 0
        if s[0] == '-':
            sign = -1
            i += 1
        elif s[0] == '+':
            i += 1
        res = 0
        while i < len(s) and s[i].isdigit():
            res = res * 10 + int(s[i])
            i += 1
        res *= sign
        INT_MIN, INT_MAX = -2**31, 2**31 - 1
        if res < INT_MIN: return INT_MIN
        if res > INT_MAX: return INT_MAX
        return res

Java Solution

class Solution {
    public int myAtoi(String s) {
        s = s.trim();
        if (s.isEmpty()) return 0;
        int sign = 1, i = 0;
        if (s.charAt(0) == '-') { sign = -1; i++; }
        else if (s.charAt(0) == '+') { i++; }
        long res = 0;
        while (i < s.length() && Character.isDigit(s.charAt(i))) {
            res = res * 10 + (s.charAt(i) - '0');
            if (sign == 1 && res > Integer.MAX_VALUE) return Integer.MAX_VALUE;
            if (sign == -1 && -res < Integer.MIN_VALUE) return Integer.MIN_VALUE;
            i++;
        }
        return (int) (res * sign);
    }
}
Watch Interactive Video on Leo Academy Main App