图解算法和数据结构部分题目
1.不适用库函数的字符串转整数。要有符号位的判定:有无?+-?使用ord() 用ascii编码差返回数字,循环添加数字时使用累乘累加的方法,而不是int(str)。
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
str = str.strip() # 去空格
if not str:
return 0
res, i, sign = 0, 1, 1 # res 为数字拼接结果,i 为数字位开始,sign为正负号
int_max, int_min, bndry = 2 ** 31-1, -2**31, 2**31 // 10 # 边界定义
if str[0] == '-': # 如果是负数
sign = -1
elif str[0] != '+': # 如果没有符号
i = 0
for c in str[i:]:
if c not in '0123456789':break # 不是数字,跳出
if res > bndry or res == bndry and c > '7': # 越界输出
return int_max if sign == 1 else int_min
res = 10 * res + ord(c) - ord('0') # 累加数字
return sign*res # 乘上符号,返回