AcWing 87. 把字符串转换成整数 - Python3
原题链接
中等
作者:
KYCygni
,
2021-03-31 13:34:32
,
所有人可见
,
阅读 230
Python3 代码
class Solution(object):
def strToInt(self, str):
"""
:type str: str
:rtype: int
"""
MAX_INT = 2147483647
MIN_INT = -2147483648
num = 0
sign = 1
k = 0
# trim
while k < len(str) and str[k] == " ":
k += 1
# read sign
for i in range (k, len(str)):
if str[i] == "-":
sign = -1
continue
if str[i] == "+":
continue
if str[i] < "0" or str[i] > "9":
break
num = num * 10 + int(str[i])
num *= sign
if num > MAX_INT:
return MAX_INT
if num < MIN_INT:
return MIN_INT
return num