8. string conversion integer (atoi)
Topic links: https://leetcode-cn.com/problems/string-to-integer-atoi/
Difficulty: Medium
Title Description
Atoi you to implement a function, it can convert a string to an integer.
First, the function will begin with a space character discard useless if necessary, until the find to the first non-space character so far.
When we find the first non-space character is a positive or negative number, the combination of the symbols as much as possible with consecutive numbers up later, as the sign of integer; if the first non-space character is figures, which directly after the continuous numeric characters are combined to form an integer.
In addition to the string after a valid integer part may also exist extra characters, these characters can be ignored, they should not affect a function.
Note: if the character string in the first non-space character is not a valid integer character string is empty or contains only white space character string, then you will not need to be a function of conversion.
In any case, if the function can not effectively convert, 0 is returned.
Description:
We assume that the size of the environment can store 32-bit signed integer, then the value range of [-2 31 is 2 31 is - 1] If the value exceeds this range, return INT_MAX (2 31 is -. 1) or INT_MIN (-2 31 is ).
Examples
Example 1:
Input: "42"
Output: 42
Example 2:
Input: "-42"
Output: -42
explained: the first non-blank character '-', it is a negative sign.
We will all digital consecutive negative number and later combined as much as possible, and finally get -42.
Example 3:
Input: "4193 words with"
Output: 4193
Explanation: converting the digital OFF '3', because the next character is not numeric.
Example 4:
Input: "987 words and"
Output: 0
Explanation: the first non-space character is a 'w', but it is not a positive number or negative number.
Therefore, the conversion can not be performed effectively.
Example 5:
Input: "-91283472332"
Output: -2147483648
explanation: the number "-91283472332" Over the range of 32-bit signed integer.
So return INT_MIN (-231).
Code
class Solution:
def myAtoi(self, str: str) -> int:
# str = str.replace(' ','')
flag = 1 # 1表示正数
head_num = 1
num = 0
for char in str:
if char == ' ':
if head_num == 1:
continue
break
elif char <= '9' and char >= '0' or char == '-' or char == '+':
if char == '-' or char == '+':
if head_num == 0:
break
flag = -1 if char == '-' else 1
head_num = 0
else:
num = num*10 + int(char)
head_num = 0
else:
break
if flag*num > 2**31-1:
return flag*2**31-1
elif flag*num < -2**31:
return flag*2**31
return flag*num