将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。
思路:
不能用库函数,只能用判断正负,然后一个数位一个数位的加起来。数字在ASCII中是48~57,判断范围确定是否是合法数值。
res=0
plus,flag=1,1
if not s:
return 0;
if s[0]=="-" or s[0]=="+":
if s[0]=="-":
flag=-1
s=s[1:]
for i in range(len(s)-1,-1,-1):
if s[i]<='9' and s[i]>='0':
res=res+(ord(s[i])-48)*plus
plus*=10
else:
return 0
return res*flag