题目描述
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
思路:
本题考查对问题理解的全面性。要考虑负数情况,考虑非法字符串情况。
# -*- coding:utf-8 -*-
class Solution:
def StrToInt(self, s):
# write code here
if not s:
return 0
dicts = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
res = []
for i in s:
if i in dicts.keys():
res.append(dicts[i])
elif i == "+" or i == "-":
continue
else:
return 0
ans = 0
for i in res:
ans = ans*10 + i
if s[0] == "-":
return 0-ans
return ans