This is a question on Leetcode: Convert a string to an integer.
The topics are as follows:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, the starting from this character, takes a optional initial plus or minus sign followed by as many numerical digits as P Ossible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which is ignored and has no Effe CT on the behavior of this function.
If the first sequence of non-whitespace characters in STR isn't a valid integral number, or if no such sequence exists be Cause either str is empty or it contains only whitespace characters, no conversion is performed.
If No valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, Int_max (2147483647) or int_min ( -2147483648) is Returne D.
Python Code:
Import re
class solution (object):
def myatoi (self, str): "" "
: Type str:str
: Rtype:int
" ""
r = Re.match ("[+-]?[ 0-9]+ ", Str.strip ())
if not r:
return 0
y = Int (R.group ())
if y < -2147483648:
y = -2147483648
if y > 2147483647:
y = 2147483647
return y
This code uses the Python regular expression module: Import re.
After submission, the details of this Python code are as follows:
Python code is easy to understand, but it takes 10 times times as much time as C and C + +.