-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path8. String to Integer (atoi).py
More file actions
58 lines (49 loc) · 1.25 KB
/
8. String to Integer (atoi).py
File metadata and controls
58 lines (49 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# -*- coding: utf-8 -*-
# @Time : 2019/3/2 18:11
# @Author : xulzee
# @Email : xulzee@163.com
# @File : 8. String to Integer (atoi).py
# @Software: PyCharm
class Solution:
def getnum(self, str: str) -> int:
nums = ""
for j in str:
if not j.isdigit():
break
nums += j
if nums != "":
nums = int(nums)
else:
nums = 0
return nums
def myAtoi(self, str: str) -> int:
if str == "":
return 0
INT_MAX = 0x7fffffff
INT_MIN = -0x80000000
# 去前缀空
for i in range(len(str)):
if str[i] != " ":
str = str[i:]
break
nums = ""
if str[0] == "-":
nums = self.getnum(str[1:])
nums = -nums
elif str[0] == "+":
nums = self.getnum(str[1:])
elif str[0].isdigit():
nums = self.getnum(str)
else:
return 0
if nums == "":
return 0
#
if nums <= INT_MIN:
return INT_MIN
if nums >= INT_MAX:
return INT_MAX
return nums
if __name__ == '__main__':
A = " 0000000000000 "
print(Solution().myAtoi(A))