String to Integer (atoi)

Problem

Implement atoi: convert a string to a 32-bit signed integer, handling leading whitespace, an optional sign, and stopping at the first non-digit.

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

Input:  s = "4193 with words"
Output: 4193

Python Solution

def my_atoi(s):
    s = s.strip()
    if not s:
        return 0
    i = 0
    sign = 1
    if s[i] in "+-":
        sign = -1 if s[i] == "-" 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(-2**31, min(result, 2**31 - 1))

C++ Solution

int myAtoi(string s) {
    int i = 0, n = s.size();
    while (i < n && s[i] == ' ') i++;
    int sign = 1;
    if (i < n && (s[i] == '+' || s[i] == '-')) {
        sign = (s[i] == '-') ? -1 : 1;
        i++;
    }
    long result = 0;
    while (i < n && isdigit(s[i])) {
        result = result * 10 + (s[i] - '0');
        if (sign * result > INT_MAX) return INT_MAX;
        if (sign * result < INT_MIN) return INT_MIN;
        i++;
    }
    return (int)(sign * result);
}

Java Solution

class Solution {
    public 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) == '-')) {
            sign = (s.charAt(i) == '-') ? -1 : 1;
            i++;
        }
        long result = 0;
        while (i < n && Character.isDigit(s.charAt(i))) {
            result = result * 10 + (s.charAt(i) - '0');
            if (sign * result > Integer.MAX_VALUE) return Integer.MAX_VALUE;
            if (sign * result < Integer.MIN_VALUE) return Integer.MIN_VALUE;
            i++;
        }
        return (int) (sign * result);
    }
}

Complexity

Time: O(n) — the string is scanned once from left to right. Space: O(1) — only a few counters are kept; overflow is checked against 32-bit integer bounds at every digit.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.