KatInterview

8. String to Integer (atoi)

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to implement a function that mimics the behavior of the standard C atoi function. This involves parsing a string to find an integer at the beginning of it. The core challenges are:

Solution

String to Integer (atoi) in Python

class Solution:
    def myAtoi(self, s: str) -> int:
        i = 0
        n = len(s)
        
        # 1. Read and ignore any leading whitespace.
        while i < n and s[i] == ' ':
            i += 1
        
        # 2. Check for sign.
        sign = 1
        if i < n and (s[i] == '+' or s[i] == '-'):
            if s[i] == '-':
                sign = -1
            i += 1
            
        # 3. Read in digits.
        num = 0
        while i < n and s[i].isdigit():
            num = num * 10 + int(s[i])
            i += 1
            
        # 4. Apply sign.
        num *= sign
        
        # 5. Clamp to 32-bit integer range.
        INT_MAX = 2**31 - 1
        INT_MIN = -2**31
        
        if num > INT_MAX:
            return INT_MAX
        if num < INT_MIN:
            return INT_MIN
            
        return num

String to Integer (atoi) in Java

class Solution {
    public int myAtoi(String s) {
        int i = 0;
        int n = s.length();
        
        // 1. Read and ignore any leading whitespace.
        while (i < n && s.charAt(i) == ' ') {
            i++;
        }
        
        // 2. Check for sign.
        int sign = 1;
        if (i < n && (s.charAt(i) == '+' || s.charAt(i) == '-')) {
            sign = (s.charAt(i) == '-') ? -1 : 1;
            i++;
        }
        
        long num = 0; // Use long to handle potential overflow during calculation.
        
        // 3. Read in digits until a non-digit character or end of string.
        while (i < n && Character.isDigit(s.charAt(i))) {
            num = num * 10 + (s.charAt(i) - '0');
            
            // 4. Handle overflow.
            // If the number exceeds the 32-bit integer range, clamp it.
            if (sign == 1 && num > Integer.MAX_VALUE) {
                return Integer.MAX_VALUE;
            }
            if (sign == -1 && -num < Integer.MIN_VALUE) {
                return Integer.MIN_VALUE;
            }
            i++;
        }
        
        // Apply sign and cast to int.
        return (int)(sign * num);
    }
}

String to Integer (atoi) in C++

class Solution {
public:
    int myAtoi(string s) {
        int i = 0;
        int n = s.length();
        
        // 1. Read and ignore any leading whitespace.
        while (i < n && s[i] == ' ') {
            i++;
        }
        
        // 2. Check for sign.
        int sign = 1;
        if (i < n && (s[i] == '+' || s[i] == '-')) {
            sign = (s[i] == '-') ? -1 : 1;
            i++;
        }
        
        long long num = 0; // Use long long to handle potential overflow during calculation.
        
        // 3. Read in digits until a non-digit character or end of string.
        while (i < n && isdigit(s[i])) {
            num = num * 10 + (s[i] - '0');
            
            // 4. Handle overflow.
            // If the number exceeds the 32-bit integer range, clamp it.
            if (sign * num > INT_MAX) {
                return INT_MAX;
            }
            if (sign * num < INT_MIN) {
                return INT_MIN;
            }
            i++;
        }
        
        // Apply sign and cast to int.
        return (int)(sign * num);
    }
};

String to Integer (atoi) in TypeScript

function myAtoi(s: string): number {
    let i = 0;
    const n = s.length;

    // 1. Read and ignore any leading whitespace.
    while (i < n && s[i] === ' ') {
        i++;
    }

    // 2. Check for sign.
    let sign = 1;
    if (i < n && (s[i] === '+' || s[i] === '-')) {
        sign = s[i] === '-' ? -1 : 1;
        i++;
    }

    // 3. Read in digits.
    let num = 0;
    while (i < n && s[i] >= '0' && s[i] <= '9') {
        num = num * 10 + (s[i].charCodeAt(0) - '0'.charCodeAt(0));
        i++;
    }
    
    // 4. Apply sign.
    num *= sign;
    
    // 5. Clamp to 32-bit integer range.
    const INT_MAX = Math.pow(2, 31) - 1;
    const INT_MIN = -Math.pow(2, 31);

    if (num > INT_MAX) {
        return INT_MAX;
    }
    if (num < INT_MIN) {
        return INT_MIN;
    }

    return num;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.