题解 | #把字符串转换成整数(atoi)#
把字符串转换成整数(atoi)
https://www.nowcoder.com/practice/d11471c3bf2d40f38b66bb12785df47f
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param s string字符串
# @return int整型
#
class Solution:
def StrToInt(self , s: str) -> int:
# write code here
s = s.strip()
flag = 1
sta = False
res = 0
for i in range(len(s)):
c = s[i]
if not c.isdigit():
if sta==False:
if c !='+' and c !='-':
return 0
elif c == '-':
flag = -1
sta = True
elif c =='+':
flag = 1
sta = True
else:
break
else:
sta = True
res = res * 10 + flag*(ord(c)-ord('0'))
if res>2**31 -1:
res = 2**31 -1
elif res<-2**31:
res = -2**31
return res
美的集团公司福利 755人发布