1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| # @Title: 把字符串转换成整数 (把字符串转换成整数 LCOF)
# @Author: 15816537946@163.com
# @Date: 2022-02-28 11:33:55
# @Runtime: 40 ms
# @Memory: 15 MB
class Solution:
def strToInt(self, str: str) -> int:
res, i, sign, length = 0, 0, 1, len(str)
int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10
if not str: return 0 # 空字符串,提前返回
while str[i] == ' ':
i += 1
if i == length: return 0 # 字符串全为空格,提前返回
if str[i] == '-': sign = -1
if str[i] in '+-': i += 1
for c in str[i:]:
if not '0' <= c <= '9' : 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
|