LeetCode Exercise 8: String to Integer (atoi)

topic

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:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.

Example

Input Output Explanation
“42” 42 -
” -42” -42 The first non-whitespace character is ‘-‘, which is the minus sign. Then take as many numerical digits as possible, which gets 42.
“4193 with words” 4193 Conversion stops at digit ‘3’ as the next character is not a numerical digit.
“words and 987” 0 The first non-whitespace character is ‘w’, which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed.
“-91283472332” -2147483648 The number “-91283472332” is out of the range of a 32-bit signed integer. Thefore INT_MIN (−231) is returned.

analyze

The input of the question is: string s
The output is: the number obtained by converting the string

This problem itself is not very difficult, but it needs to deal with many conditions, so it will be more troublesome. The following solution minimizes this judgment.

  • We first remove the spaces at the front and back ends of the string, and then judge the first character of the remaining string: if it is a +sign, it means a positive number; if it is a -sign, it means a negative number; if it is a number, it is directly converted; otherwise is another letter, ending the judgment.
  • Next, the remaining characters are judged accordingly: if it is a number, it is directly converted; otherwise, it is other letters, and the judgment is ended.
  • According to the positive and negative flags, it is judged whether it overflows.

answer

class Solution:
    def myAtoi(self, s):
        """
        :type str: str
        :rtype: int
        """
        int_max = 2 ** 31 -1 
        int_min = -2 ** 31

        s = s.strip()
        result = 0
        flag = 0

        for i in s:
            if i == '-' and flag == 0:
                flag = -1
                continue

            if i == '+' and flag == 0:
                flag = 1
                continue

            if i.isdigit():
                result = result * 10 + int(i)
            else:
                break

        if flag == -1:
            result = max(int_min, -result)
        else:
            result = min(int_max, result)

        return result

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324728795&siteId=291194637