-
Notifications
You must be signed in to change notification settings - Fork 0
/
q8_String_to_Integer.py
46 lines (40 loc) · 1.02 KB
/
q8_String_to_Integer.py
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
class Solution:
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
try:
s = str.strip()
s = list(s)
num, sign = 0, 1
if s[0] == "-" or s[0] == "+":
if s[0] == "-":
sign = -1
del s[0]
for c in s:
if c.isdigit():
num = 10 * num + int(c)
else:
break
return min(2147483647, max(-2147483648, sign * num))
except:
return 0
def myAtoi_RegEx(self, str):
"""
:type str: str
:rtype: int
^: start
[+-]?: 1 or 0 [+-]
\d+: any numbers
"""
import re
str = str.strip()
try:
str = re.search(r'^[+-]?\d+', str).group()
n = int(''.join(str))
return min(2147483647, max(-2147483648, n))
except:
return 0
s=Solution()
print(s.myAtoi_RegEx("+-342ewf"))