题目描述:将一个字符串转换成一个整数(实现Integer.valueOf(string) 的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。
Solutions
这个还是比较简单的,主要考虑清楚需要注意的字符情况。
# -*- coding:utf-8 -*-
class Solution:
def StrToInt(self, s):
# write code here
if s is None:
return 0
cs_dict = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
'-', '+']
res = 0
signal = 1
for i in range(len(s)):
if s[i] not in cs_dict:
return 0
if s[i] == '-':
signal = -1
elif s[i] == '+':
continue
else:
res = res *10 + (ord(s[i]) - ord('0'))
return res * signal
# 运行时间:25ms
# 占用内存:5868k
然而很明显,调用了 ord 计算字符相差多少,这样不是很优雅,别人的做法还是值得学习:
# -*- coding:utf-8 -*-
class Solution:
def StrToInt(self, s):
# write code here
numstrs=['0','1','2','3','4','5','6','7','8','9']
sum = 0
label=1
for i in range(len(s)):
if i==0:
if s[i]=='-':
label=-1
continue
elif s[i]=='+':
continue
if s[i] in numstrs:
sum =sum*10+numstrs.index(s[i])
else:
sum = 0
break
return sum*label