Problem: String to integer(leetcode)
Implement
atoi
which converts a string to an integer.The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because 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.
Note:
- Only the space character
' '
is considered as a whitespace character.- Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [-2^31, 2^31-1]. If the numerical value is out of the range of representable values, (2^31-1) or -2^31 is returned.
My solution:
I have implemented this code below. I have noted down the requirements and implemented the code. It was hard to keep track of all the details. Before acceptance, I got WA 4 times(and it seems like the code I've written is not compact).
class Solution:
def myAtoi(self, s: str) -> int:
l = len(s)
if l==0:
print(1)
return 0
if l==1:
if s==" " or s=="+" or s=="-":
return 0
elif(s.isnumeric()):
return int(s)
else:
return 0
res = ""
i = 0
while(i<l and s[i]==" "):
i+=1
if i==l:
return 0
ispos = False
if(s[i]=="+"):
ispos = True
i+=1
isnegative = False
if(s[i]=='-' and not ispos):
isnegative = True
i+=1
if(i<len(s) and not s[i].isnumeric() and s[i]!='+' and s[i]!='-'):
return 0
while(i<l):
if s[i].isnumeric():
res += s[i]
else:
break
i+=1
if len(res)>0:
x = int(res)
else:
return 0
if isnegative:
if x>=(1<<31):
return -(1<<31)
x *= -1
if x>=((1<<31) - 1):
return (1<<31)-1
return x
Can anyone write a compact code for this problem?
I also like to know if there is an approach to solve this kind of implementation problems so that I can write compact code. Can anyone share any better method to analyze this type of implementation problem? (or, any suggestion to be better in solving this kind of problems where we need to keep track of many things)