LeetCode_One question per day_python_Question 8 string conversion integer

Please implement an atoi function to convert a string to an integer.

First, the function discards useless beginning space characters as needed, until it finds the first non-space character. The following conversion rules are as follows:

If the first non-blank character is a positive or negative sign, combine this sign with as many consecutive numeric characters as possible to form a signed integer.
If the first non-blank character is a number, it is directly combined with the following consecutive number characters to form an integer.
The string may also have extra characters after the valid integer part, so these characters can be ignored and they should not affect the function.
Note: If the first non-space character in the string is not a valid integer character, the string is empty, or the string contains only blank characters, your function does not need to be converted, that is, it cannot be converted effectively.

In any case, if the function cannot perform a valid conversion, please return 0.

prompt:

The blank characters in this question only include the space character ''.
Assuming that our environment can only store 32-bit signed integers, the value range is [−231, 231 − 1]. If the value exceeds this range, please return INT_MAX (231 − 1) or INT_MIN (−231).
 

Example 1:

Input: "42"
Output: 42
Example 2:

Input: "-42"
Output: -42
Explanation: The first non-blank character is'- ', which is a negative sign.
     We try our best to combine the minus sign with all subsequent numbers, and finally get -42.
Example 3:

Input: "4193 with words"
Output: 4193
Explanation: The conversion ends at the number '3' because the next character is not a number.
Example 4:

Input: "words and 987"
Output: 0
Explanation: The first non-blank character is'w', but it is not a number or a positive or negative sign.
     Therefore, effective conversion cannot be performed.
Example 5:

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

Source: LeetCode
 

class Solution:
    def myAtoi(self, str: str) -> int:
        INT_MAX = 2 ** 31 - 1
        INT_MIN = -2 ** 31
        i = 0
        n = len(str)            # 长度
        flag = 1                # 正负
        res = 0                 # 结果
        while i < n and str[i] == ' ':
            i += 1
        if i == n or n == 0:
            return 0
        if str[i] == '-':
            flag = -flag
        if str[i] == '+' or str[i] == '-':
            i += 1
        while i < n and '0' <= str[i] <= '9':
            res = res * 10 + int(str[i]) -int('0')
            i += 1
        res = flag * res
        if res > INT_MAX:
            return INT_MAX
        return INT_MIN if res < INT_MIN else res

 

Guess you like

Origin blog.csdn.net/qq_42548880/article/details/108573175