8. 字符串转换整数 (atoi)
请你来实现一个 myAtoi(string s) 函数,使其能将字符串转换成一个 32 位有符号整数。
函数 myAtoi(string s) 的算法如下:
空格:读入字符串并丢弃无用的前导空格(
" ")符号:检查下一个字符(假设还未到字符末尾)为
'-'还是'+'。如果两者都不存在,则假定结果为正。转换:通过跳过前置零来读取该整数,直到遇到非数字字符或到达字符串的结尾。如果没有读取数字,则结果为0。
舍入:如果整数数超过 32 位有符号整数范围
[−231, 231 − 1],需要截断这个整数,使其保持在这个范围内。具体来说,小于−231的整数应该被舍入为−231,大于231 − 1的整数应该被舍入为231 − 1。
返回整数作为最终结果。
class Solution:
def myAtoi(self, s: str) -> int:
n = len(s)
positive = True
i = 0
start_int = False
result = 0
min_value,max_value = -2**31,2**31-1
while i<len(s):
if s[i] == "-" and not start_int:
positive = False
start_int = True
elif s[i] == "+" and not start_int:
positive = True
start_int = True
elif s[i] == " " and not start_int:
pass
elif s[i] in ["0","1","2","3","4","5","6","7","8","9"]:
if not start_int:
start_int = True
result = result*10+int(s[i])
else:
break
i+=1
result = result*-1 if not positive else result
result = max(result,min_value) if not positive else min(result,max_value)
return result
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 逻漫星空
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果