将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。
Iuput:
+2147483647
1a33
Output:
2147483647
0
解题思路
class Solution:
def StrToInt(self, s):
# write code here
if not s:
return 0
res =0
numbers = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
for i in range(len(s)):
if i==0 and (s[i] == '+' or s[i] == '-') :
continue
if s[i]<'0' or s[i]>'9':
return False
res = res * 10 + numbers[s[i]]
if s[0] == '-':
res = 0 - res
return res
python中字符串之间不能使用减法
TypeError: unsupported operand type(s) for -: 'str' and 'str'