题目:https://leetcode.com/problems/string-to-integer-atoi/
8. String to Integer (atoi)
Medium
16849704Add to ListShare
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 (−2^31) is returned.
题意:题目意思是请你来实现一个 atoi 函数,使其能将字符串转换成整数。
首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。接下来的转化规则如下:
- 如果第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字字符组合起来,形成一个有符号整数。
- 假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成一个整数。
- 该字符串在有效的整数部分之后也可能会存在多余的字符,那么这些字符可以被忽略,它们对函数不应该造成影响。
- 其他情况返回0
解题思路:
1.对字符串进行处理,先把字符串首尾的空格去掉;
2.然后判断是否为空字符串,是空则返回0
3.对字符串进行处理,提取起始符为(0个或者1个【+/-】)且后面紧跟着(1个或多个数字)的字符串存在列表中,列表中只有一个元素。
4.判断提取的内容是否为空,为空则说明无此情况,返回0
5.将列表元素转为整型数字
6.返回数字,且判断是否在范围内,max(new_num, -2 ** 31)表示 new_num<=-2 ** 31,min(max(new_num, -2 ** 31), 2 ** 31-1)表示2 ** 31-1<=new_num<=-2 ** 31; 可以这么理解。
解题代码(python):
import re
class Solution:
def myAtoi(self, str: str) -> int:
num = str.strip()#去除首尾空格
if not num:
return 0
new_num = re.findall(r"^[+-]?\d+",num) #扫描出来的结果生成列表
# print(new_num,len(new_num))
if not new_num:
return 0
new_num = int(new_num[0])
return min(max(new_num, -2 ** 31), 2 ** 31-1) #类似 大于等于和小于等于,1<= x<=2
print(Solution().myAtoi("42"))
print(Solution().myAtoi("-91283472332"))
#42
#-2147483648