-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathatoi.py
More file actions
50 lines (43 loc) · 909 Bytes
/
Copy pathatoi.py
File metadata and controls
50 lines (43 loc) · 909 Bytes
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
import sys
# https://leetcode.com/problems/string-to-integer-atoi/
def atoi(str):
str = str.strip()
if len(str) == 0:
return 0
isNegative = False
isDigit = False
if str[0] == '-':
isNegative = True
elif str[0] == '+':
pass
elif str[0].isdigit():
isDigit = True
else:
return 0
i = 0
if isDigit == False:
i = 1
num = ''
while i < len(str):
if str[i].isdigit() == True:
num += str[i]
else:
break
i += 1
if num == '':
return 0
if isNegative:
num = 0 - int(num)
else:
num = int(num)
if num > 2 ** 31 - 1:
return 2 ** 31 - 1
elif num < -(2 ** 31):
return -(2 ** 31)
return num
def main():
str = input('input: ')
num = atoi(str)
print('output: ', num)
if __name__ == '__main__':
main()