LeetCode练习8:String to Integer (atoi)

题目

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.

分析

题目的输入为:字符串 s
输出为:字符串转化得到的数字

本题目难度自身并不大,但是需要处理很多条件,因此会比较麻烦。下面的解法则尽量减少这种判断。

  • 我们首先将字符串前后两端的空格去掉,然后判断剩余字符串的第一个字符:如果是+号,则表示是正数;如果是-号,则表示是负数;如果是数字,则直接进行转换;否则是其他字母,结束判断。
  • 接下来对剩余字符进行相应的判断:如果是数字,则直接进行转换;否则是其他字母,结束判断。
  • 根据正负数标志,判断是否溢出。

解答

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

猜你喜欢

转载自blog.csdn.net/u011954995/article/details/80047571