class Solution:
# @return an integer
def atoi(self, str):
str = str.strip()
str = re.findall('(^[\+\0]*\d+)\D*', str)
try:
result = int(''.join(str))
MAX_INT = 2147483647
MIN_INT = 2147483648
if result > MAX_INT > 0:
return MAX_INT
elif result < MIN_INT < 0:
return MIN_INT
else:
return result
except:
return 0
Python solution based on RegEx


@zzhai said in Python solution based on RegEx:
^[+]?\d+
Hi, I'm new to python and I'm confused by this "^[+]?\d+"
How exactly does this work? Thanks

@yxyang this is called regular expression, details in python doc .
The whole expression is(^[\+\0]*\d+)\D*
, where^
matches the beginning of the string,[]
matches any single character inside the bracket,*
means preceding character[\+\0]
can be matched zero or more times,\d
means decimal digits,+
means preceding character\d
must appear at least once,\D
means nondigits.

class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
if not str:
return 0
INT_MAX = 2147483647
INT_MIN = 2147483648
import re
newstr=""
match = re.search("^[+]{0,1}[09]+",str.strip())if match: newstr=int(match.group()) if(INT_MIN < newstr < INT_MAX ): return newstr else: if newstr <= INT_MIN : return INT_MIN else: return INT_MAX return 0

@Google I came up with a very similar one, but I did the char to int conversion manually...
class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int """ import re p=re.compile('\s*([+]?)(\d*)') n=p.match(str) if n.group(1)=='': sign = 1 else: sign = 1 number=0 for i in range (0,len(n.group(2))): number=number*10+(ord(n.group(2)[i])ord('0')) number=number*sign if (number>2147483647): number=2147483647 if (number<2147483648): number=2147483648 return number