Problem

Implement atoi: parse a string into a 32-bit signed integer. Skip whitespace, handle optional sign, read digits, clamp to [-2³¹, 2³¹-1].

Example

Input:  "   -42"
Output: -42

Solution

Step through: skip spaces, read sign, accumulate digits while clamping to int range.

def my_atoi(s):
    INT_MAX = 2**31 - 1
    INT_MIN = -2**31
    s = s.lstrip()
    if not s: return 0
    sign = 1
    i = 0
    if s[0] in '+-':
        sign = -1 if s[0] == '-' else 1
        i = 1
    result = 0
    while i < len(s) and s[i].isdigit():
        result = result * 10 + int(s[i])
        i += 1
    result *= sign
    return max(INT_MIN, min(INT_MAX, result))
function myAtoi(s) {
    const MAX = 2**31 - 1, MIN = -(2**31);
    s = s.trimStart();
    if (!s) return 0;
    let sign = 1, i = 0;
    if (s[0] === '+' || s[0] === '-') {
        sign = s[0] === '-' ? -1 : 1;
        i = 1;
    }
    let result = 0;
    while (i < s.length && /d/.test(s[i])) {
        result = result * 10 + Number(s[i]);
        i++;
    }
    result *= sign;
    return Math.max(MIN, Math.min(MAX, result));
}
int myAtoi(string s) {
    int i = 0, n = s.size(), sign = 1;
    long result = 0;
    while (i < n && s[i] == ' ') i++;
    if (i < n && (s[i] == '+' || s[i] == '-')) {
        sign = s[i] == '-' ? -1 : 1;
        i++;
    }
    while (i < n && isdigit(s[i])) {
        result = result * 10 + (s[i] - '0');
        if (result * sign > INT_MAX) return INT_MAX;
        if (result * sign < INT_MIN) return INT_MIN;
        i++;
    }
    return (int)(result * sign);
}
public int myAtoi(String s) {
    int i = 0, n = s.length(), sign = 1;
    long result = 0;
    while (i < n && s.charAt(i) == ' ') i++;
    if (i < n && (s.charAt(i) == '+' || s.charAt(i) == '-')) {
        sign = s.charAt(i) == '-' ? -1 : 1;
        i++;
    }
    while (i < n && Character.isDigit(s.charAt(i))) {
        result = result * 10 + (s.charAt(i) - '0');
        if (result * sign > Integer.MAX_VALUE) return Integer.MAX_VALUE;
        if (result * sign < Integer.MIN_VALUE) return Integer.MIN_VALUE;
        i++;
    }
    return (int)(result * sign);
}

Complexity

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

Explanation

The clamping check should happen during accumulation to avoid overflow. Use long type in C++/Java for headroom.

Share this article

Comments

Join the discussion. Got a question, found an issue, or want to share your experience?

Leave a Comment

Your email stays private. We just use it for replies.

Nothing to preview yet.

Use **bold**, *italic*, `code`, ```code blocks```, [link](url), > quote, - list