String to Integer (atoi)

Medium
36.

String to Integer (atoi)

String to Integer (atoi) is a medium coding problem on strings and math, asked in Databricks interviews.

Implement myAtoi(s):

  1. Skip leading spaces.
  2. Read an optional +/- sign.
  3. Read digits until a non-digit (or the end).
  4. Clamp the result into the 32-bit signed range [-2147483648, 2147483647].

Anything after the number is ignored; if no digits were read, return 0.

Example 1

Input
s = "42"
Output
42

Example 2

Input
s = " -042"
Output
-42

Example 3

Input
s = "1337c0d3"
Output
1337

Example 4

Input
s = "-91283472332"
Output
-2147483648
Explanation
Clamped to INT_MIN.

Constraints

  • 0 <= s.length <= 25
  • s consists of digits, letters, spaces, '+', '-' and '.'
Write your solution here. Running it against the tests needs a free account — what you type comes with you.Sign in to run
/**
 * @param {string} s
 * @return {number}
 */
var myAtoi = function(s) {
    // Write your code here
    
};

Sign in to run your own test cases

Sign in

String to Integer (atoi) — Solution in Python, Java & C++

String to Integer (atoi) solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. A medium problem.

String to Integer (atoi) is a medium coding problem on strings and math, asked in Databricks interviews.

  • Difficulty: Medium
  • Topics: Strings, Math
  • Asked at: Databricks
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

Implement myAtoi(s):

  1. Skip leading spaces.
  2. Read an optional +/- sign.
  3. Read digits until a non-digit (or the end).
  4. Clamp the result into the 32-bit signed range [-2147483648, 2147483647].

Anything after the number is ignored; if no digits were read, return 0.

Example 1

Input: s = "42"
Output: 42

Example 2

Input: s = "   -042"
Output: -42

Example 3

Input: s = "1337c0d3"
Output: 1337

Example 4

Input: s = "-91283472332"
Output: -2147483648
Explanation: Clamped to INT_MIN.

Constraints

  • 0 <= s.length <= 25
  • s consists of digits, letters, spaces, '+', '-' and '.'

Hints for String to Integer (atoi)

  1. Hint 1

    Process in three phases: whitespace, sign, digits — each phase advances an index.

  2. Hint 2

    Clamp during accumulation, not only at the end.

How to solve String to Integer (atoi)

A strict three-phase parse — whitespace, then an optional sign, then digits — with the overflow check applied before each digit is absorbed, not after. Checking afterwards is too late in fixed-width integer languages, where the value has already wrapped.

Approach

  1. Skip leading spaces.
  2. Read an optional single + or - and remember the sign.
  3. Read digits, accumulating result = result * 10 + digit.
  4. Before each absorption, test whether it would exceed the 32-bit range; if so return the clamp immediately.
  5. Stop at the first non-digit and return the signed result — no digits at all means 0.

Why it works

The guard result > INT_MAX / 10, or result == INT_MAX / 10 and digit > 7 is exactly the condition for result * 10 + digit to exceed 2147483647, since INT_MAX ends in 7. Testing before multiplying means the overflow never actually happens. Clamping to INT_MIN on the negative side is correct even though its magnitude is one larger, because any input that trips the guard is already beyond the representable range in that direction.

Complexity

  • Time — O(n)
  • Space — O(1)

Pitfalls

  • Check for overflow before multiplying, or the wrap has already destroyed the value.
  • Only one sign character is allowed; "+-2" parses no digits and returns 0.
  • Leading zeros are fine and must not be mistaken for the end of the number.
  • Trailing junk is simply ignored, but junk before the digits (other than spaces and a sign) stops the parse dead.

Reference solution

Python

def myAtoi(s: str) -> int:
    INT_MAX = 2147483647
    INT_MIN = -2147483648
    i = 0
    while i < len(s) and s[i] == " ":
        i += 1
    sign = 1
    if i < len(s) and s[i] in "+-":
        if s[i] == "-":
            sign = -1
        i += 1
    num = 0
    while i < len(s) and s[i].isdigit():
        num = num * 10 + int(s[i])
        if sign == 1 and num > INT_MAX:
            return INT_MAX
        if sign == -1 and -num < INT_MIN:
            return INT_MIN
        i += 1
    return sign * num

Java

public static int myAtoi(String s) {
    int i = 0, n = s.length();
    while (i < n && s.charAt(i) == ' ') i++;
    int sign = 1;
    if (i < n && (s.charAt(i) == '+' || s.charAt(i) == '-')) {
        if (s.charAt(i) == '-') sign = -1;
        i++;
    }
    int result = 0;
    while (i < n) {
        char c = s.charAt(i);
        if (c < '0' || c > '9') break;
        int d = c - '0';
        if (result > 214748364 || (result == 214748364 && d > 7)) {
            return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
        }
        result = result * 10 + d;
        i++;
    }
    return sign * result;
}

C++

int myAtoi(string s) {
    int i = 0, n = (int) s.size();
    while (i < n && s[i] == ' ') i++;
    int sign = 1;
    if (i < n && (s[i] == '+' || s[i] == '-')) {
        if (s[i] == '-') sign = -1;
        i++;
    }
    int result = 0;
    while (i < n) {
        char c = s[i];
        if (c < '0' || c > '9') break;
        int d = c - '0';
        if (result > 214748364 || (result == 214748364 && d > 7)) {
            return sign == 1 ? 2147483647 : -2147483648;
        }
        result = result * 10 + d;
        i++;
    }
    return sign * result;
}

JavaScript

var myAtoi = function(s) {
    const INT_MAX = 2147483647, INT_MIN = -2147483648;
    let i = 0;
    while (i < s.length && s[i] === " ") i++;
    let sign = 1;
    if (i < s.length && (s[i] === "+" || s[i] === "-")) {
        if (s[i] === "-") sign = -1;
        i++;
    }
    let num = 0;
    while (i < s.length && s[i] >= "0" && s[i] <= "9") {
        num = num * 10 + (s.charCodeAt(i) - 48);
        if (sign === 1 && num > INT_MAX) return INT_MAX;
        if (sign === -1 && -num < INT_MIN) return INT_MIN;
        i++;
    }
    return sign * num;
};

Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 515 strings problems · the whole catalogue

Learn the technique: Strings