8. 字符串转换整数 (atoi) - 力扣(LeetCode)




下面是 myAtoi 的实现:
def myAtoi(s: str) -> int:
s = s.lstrip() # 去掉前导空格
if not s:
return 0
sign = 1
index = 0
if s[0] == '-':
sign = -1
index += 1
elif s[0] == '+':
index += 1
result = 0
while index < len(s) and s[index].isdigit():
result = result * 10 + int(s[index])
index += 1
result *= sign
# 32位整数范围
int_min, int_max = -2**31, 2**31 - 1
if result < int_min:
return int_min
if result > int_max:
return int_max
return result
这个实现按顺序处理了空格、符号、数字转换和边界处理,确保符合 32 位整数的约束。可以测试不同的输入来验证其正确性!
596

被折叠的 条评论
为什么被折叠?



