Title Description
Converts a string into an integer, the request can not use the library function converts the integer string. Value of 0 or a character string is not a valid return value 0
Input Description
enter a character string including alphanumeric symbols, can be null
Output Description
If the expression is valid number value is returned, otherwise 0
Example 1
Input
+2147483647
1a33
Output
2147483647
0
Part of the answer, more clever
class Solution:
def StrToInt(self, s):
# write code here
if s is '':
return 0
numlist = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
res = 0
label = 1
first = s[0]
if first == '+':
label = 1
s = s[1:]
elif first == '-':
label = -1
s = s[1:]
for string in s:
if string not in numlist:
return 0
else:
res = res * 10 + numlist.index(string)
return label * res