Leetcode 8. String to Integer (atoi)

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

 

Requirements for atoi:The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

Analysis:

Lots of corner case to be considered:

  • number start or end with black space – use str.trim()
  • number start with + / – – with a sign
  • number out of rangeĀ Integer range [-2147483648, 2147483647]

Note: to get the integer value of a string number, like ‘1’, we can use the charĀ – ‘0’

For integer out of range, we need to check the res with the Integer.MAX_VALUE. If the last value is larger than 8 and the res = MAX /10, then it’s overflow.

To check a char is digit, we can use Character.isDigit(char).

Time complexity: O(n)

Space complexity: O(1)

Code is below:

public class Solution {
    public int myAtoi(String str) {
        // O(n) O(1)
        
        if (str == null || str.length() == 0) {
            return 0;
        }
        
        // To get rid of the leading and tailing blank space like " -1234 "
        str = str.trim();
        
        // Set the sign
        int sign = 1;
        
        int i = 0;
        
        // Check of "+" and "-"
        if (str.charAt(0) == '+') {
            i++;
        }
        
        if (str.charAt(0) == '-') {
            sign = -1;
            i++;
        }
        
        int res = 0;
        
        while (i < str.length() && Character.isDigit(str.charAt(i))) {             // Get the current digit             int digit = (int) (str.charAt(i) - '0');                          // Integer range [-2147483648, 2147483647]             if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && digit >= 8)) {
                return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            
            res = res * 10 + digit;
            i++;
        }
        
        return sign * res;
   
        //return Integer.valueOf(str);
    }
}