Algo-Sim › Math & Geometry

String to Integer (atoi)

Medium · Math & Geometry · step through it in Java, Python and C++ on your own input

Parse an int: skip leading spaces, read one optional sign, then digits until the first non-digit, clamping to the 32-bit range with the same check as Reverse Integer.

Problem

Implement myAtoi(s): skip leading spaces, read an optional + or −, then read digits until a non-digit or the end, ignoring leading zeros. If no digits are read the result is 0. Clamp the result to [−2³¹, 2³¹ − 1].

Constraints

Edge cases to test

Follow-up questions

Why check overflow before each multiply?
Once the value has overflowed the information is lost; checking result > (MAX − d) / 10 first keeps it exact.
How would you design it as a state machine?
States start → sign → digits → end with transitions on character classes; this keeps every edge case ("+-1", " +0 123") explicit.

Solution

Java

public int myAtoi(String s) {
    int i = 0, n = s.length(), sign = 1, result = 0;
    while (i < n && s.charAt(i) == ' ') i++;
    if (i < n && (s.charAt(i) == '+' || s.charAt(i) == '-'))
        sign = s.charAt(i++) == '-' ? -1 : 1;
    while (i < n && Character.isDigit(s.charAt(i))) {
        int d = s.charAt(i++) - '0';
        // The same check as Reverse Integer, before result * 10 can overflow.
        if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && d > 7))
            return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
        result = result * 10 + d;
    }
    return sign * result;
}

Python

def my_atoi(s):
    INT_MAX, INT_MIN = 2**31 - 1, -(2**31)
    i, n, sign, result = 0, len(s), 1, 0
    while i < n and s[i] == " ":
        i += 1
    if i < n and s[i] in "+-":
        sign = -1 if s[i] == "-" else 1
        i += 1
    while i < n and "0" <= s[i] <= "9":
        d = ord(s[i]) - ord("0")
        i += 1
        # The same check as Reverse Integer, before result * 10 can overflow.
        if result > INT_MAX // 10 or (result == INT_MAX // 10 and d > 7):
            return INT_MAX if sign == 1 else INT_MIN
        result = result * 10 + d
    return sign * result

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int myAtoi(string &s) {
        int i = 0, n = s.size(), sign = 1, result = 0;
        while (i < n && s[i] == ' ') i++;
        if (i < n && (s[i] == '+' || s[i] == '-'))
            sign = s[i++] == '-' ? -1 : 1;
        while (i < n && isdigit(s[i])) {
            int d = s[i++] - '0';
            // The same check as Reverse Integer, before result * 10 can overflow.
            if (result > INT_MAX / 10 || (result == INT_MAX / 10 && d > 7))
                return sign == 1 ? INT_MAX : INT_MIN;
            result = result * 10 + d;
        }
        return sign * result;
    }
};

More Math & Geometry problems