跳转至

8. String to Integer (atoi)

Leetcode Math String

Implement atoi which converts a string to an integer.

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.

Note:

  • Only the space character ' ' is considered as whitespace character.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^{31}, 2^{31} − 1]. If the numerical value is out of the range of representable values, INT_MAX (2^{31} − 1) or INT_MIN (−2^{31}) is returned.

Example 1:

Input: "42"
Output: 42

Example 2:

Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
             Then take as many numerical digits as possible, which gets 42.

Example 3:

Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:

Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical 
             digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
             Thefore INT_MIN (−231) is returned.

分析

这道题目其实出的很好,非常具有实际意义。我直接借鉴的Java中的Integer.parseInt()的写法。它具有一下特点:

  • 把结果写成负数结果,因为负数的范围比正数大,比较方便。
  • 分别判断减法溢出和乘法溢出。
public int myAtoi(String str) {
        str = str.trim(); // 除去空格
        int len = str.length(); //数字长度
        if (len == 0) return 0; // 特殊情况:空字符串
        boolean isPositive = true; // 数字正负符号
        int i = 0; // index
        int result = 0; // 转换结果
        int limit = -Integer.MAX_VALUE; // 数字下限:用来判断减法溢出
        // 首字符是(+,-)
        if (str.charAt(0) == '+' ) {i++;}
        if (str.charAt(0) == '-')  {
            i++;
            isPositive = false;
            limit = Integer.MIN_VALUE;
        }

        boolean isStart = false; // 数字开头载入了吗?
        int multmin = limit / 10; // 数字下限:用来判断乘法溢出
        while (i < len) {
            int tail = str.charAt(i) - '0';
            // 后续字符都是数字
            if (tail > 9 || tail < 0) {
                if (!isStart) return 0; // 非有效数字,返回0
                else break;
            }

            // 乘法溢出
            if (result < multmin) {
                if (isPositive) return -limit;
                else return limit;
            }
            result *= 10;

            // 减法溢出
            if (result < limit + tail) {
                if (isPositive) return -limit;
                else return limit;
            }
            result -= tail;


            isStart = true; // 已经载入第一个数字
            i++; // 下一个数字
        }

        return isPositive ? -result : result;
}

Python

Python解答:

class Solution:
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        str_strip = str.strip() # strip whitespace
        # str is empty or it contians only white space characters, no conversion is performed
        if not len(str_strip): return 0 
        first_num = 0
        first_char = str_strip[0]
        sign = 1
        if first_char == '+':
            first_num = 1
        elif first_char == '-':
            sign = -1
            first_num = 1

        # only -,+ character
        if len(str_strip)==1 and first_num==1:
            return 0

        # check the first character of non-whitespace string is a number
        if not ('0' <= str_strip[first_num] <= '9'):
            return 0

        # remove 0 in the front of the string
        print(str_strip[first_num])
        while str_strip[first_num] == '0':
            first_num += 1
            print("OK")

        result = 0
        for char in str_strip[first_num:]:
            if ('0' <= char <= '9'):
                result = result*10 +  ord(char) - ord('0')
            # contains illegal character in the end of str
            else:
                break

        # sign +, -
        result *= sign

        if result > 2147483647:
            result = 2147483647
        elif result < -2147483647-1:
            result = -2147483647-1

        return result