题目描述
将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。
输入描述:
输入一个字符串,包括数字字母符号,可以为空
输出描述:
如果是合法的数值表达则返回该数字,否则返回0
思路:
首先判断正负
然后遍历字符串,如果不是数字就返回0
每次的更新规则相当于从高位向低位进行,就是乘以10加上当前数字
代码:
class Solution:
def StrToInt(self, s):
# write code here
if not s:
return 0
dic = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}
res = 0
is_positive = 1
if s[0] == '+':
s = s[1:]
elif s[0] == '-':
is_positive = -1
s = s[1:]
for i in s:
if i not in dic:
return 0
res = res * 10 + dic[i]
return is_positive * res