- Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathString_To_Integer.py
More file actions
Latest commit
51 lines (47 loc) · 1.33 KB
/
Copy pathString_To_Integer.py
File metadata and controls
51 lines (47 loc) · 1.33 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
"""
@author - Anirudh Sharma
"""
defmyAtoi(s: str) ->int:
# Base condition
ifsisNoneorlen(s) <1:
return0
# Max and Min values for the integers
INT_MAX=2147483647
INT_MIN=-2147483648
# Trimmed string
s=s.lstrip()
# Counter
i=0
# Flag to indicate if the number is negative
isNegative=len(s) >1ands[0] =='-'
# Flag to indicate if the number is positive
isPositive=len(s) >1ands[0] =='+'
ifisNegative:
i+=1
elifisPositive:
i+=1
# This will store the converted number
number=0
# Loop for each numeric character in the string iff numeric characters are leading
# characters in the string
whilei<len(s) and'0'<=s[i] <='9':
number=number*10+ (ord(s[i]) -ord('0'))
i+=1
# Give back the sign to the number
ifisNegative:
number=-number
# Edge cases - integer overflow and underflow
ifnumber<INT_MIN:
returnINT_MIN
ifnumber>INT_MAX:
returnINT_MAX
returnnumber
if__name__=='__main__':
print(myAtoi("42"))
print(myAtoi(" -42"))
print(myAtoi("4193 with words"))
print(myAtoi("words and 987"))
print(myAtoi("-91283472332"))
print(myAtoi("91283472332"))
print(myAtoi("9223372036854775808"))
print(myAtoi(" "))