-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAtoi.py
More file actions
32 lines (30 loc) · 843 Bytes
/
Copy pathAtoi.py
File metadata and controls
32 lines (30 loc) · 843 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
# https://www.interviewbit.com/problems/atoi/
maxInt = pow(2, 31) - 1
minInt = -pow(2, 31)
class Solution:
# @param A : string
# @return an integer
def atoi(self, A):
A = A.strip()
resStr = ""
isNegative = False
if A != "" and A[0] == "-":
isNegative = True
A = A[1:]
elif A != "" and A[0] == "+":
A = A[1:]
for i in range(len(A)):
if ord(A[i]) - ord("0") >= 0 and ord(A[i]) - ord("0") <= 9:
resStr += A[i]
else:
break
result = 0
for ch in resStr:
result = result * 10 + int(ch)
if isNegative:
result = -result
if result > maxInt:
return maxInt
if result < minInt:
return minInt
return result