题解 | 把字符串转换成整数(atoi)
把字符串转换成整数(atoi)
https://www.nowcoder.com/practice/d11471c3bf2d40f38b66bb12785df47f
class Solution: def StrToInt(self , s: str) -> int: x = 0 sign = 1 flag = True for c in s: if flag and c==' ': continue elif flag and c=='-': sign = -1 flag = False elif flag and c=='+': sign = 1 flag = False elif c.isdigit(): x = x*10+int(c) flag = False else: break if sign*x>=2**31: return 2**31-1 elif sign*x<-2**31: return -2**31 return sign*x