class Solution:
def myAtoi(self, str):
if len(str) == 0:
return 0
s = list(str.strip())
sign = 1
i = 0
dig = 0
if s[0] == '-':
sign = -1
i = 1
print(s)
while i<len(s) and s[i].isdigit():
# dig = dig*10 + ord(s[i]) - ord('0')
dig = dig * 10 + int(s[i])
i = i + 1
dig = dig * sign
return max(-1 * 2**31,min(dig , 2**31 - 1))
复习:
strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
ord() 函数返回对应的 ASCII 数值,或者 Unicode 数值。
对于超过范围就返回最大值或最小值的表达:max(-1 * 2**31,min(dig , 2**31 - 1))
本文详细介绍了如何使用Python实现myAtoi函数,该函数能够将字符串转换为整数,同时处理各种边界情况,如去除前导空格、判断正负号、处理非数字字符等。文章还解释了strip()和isdigit()方法的使用,以及如何通过ord()函数获取字符的ASCII值。

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



