winmeanyoung 2020-05-08
输入一个字符串,包括数字字母符号,可以为空
如果是合法的数值表达则返回该数字,否则返回0
# -*- coding:utf-8 -*- class Solution: def StrToInt(self, s): # write code here if len(s)==0: return 0 end = len(s)-1 begin = -1 temp = 1 int_s = 0 if s[0]==‘-‘ or s[0]==‘+‘: begin = 0 for i in range(end,begin,-1): if s[i]<‘0‘ or s[i]>‘9‘: return 0 int_s += temp*int(s[i]) temp = temp *10 if s[0]==‘-‘: int_s = -int_s return int_s
使用列表,当成大数处理,牛客一直通不过,最终还是得将字符串改为整数,很纳闷
# -*- coding:utf-8 -*- class Solution: # 大数问题 def StrToInt(self, s): # write code here if len(s) == 0: return 0 if len(s)==1 and (s[0]<‘0‘ or s[0]>‘9‘): return 0 end = len(s) - 1 begin = -1 int_s = [0]*len(s) if s[0] == ‘-‘ or s[0] == ‘+‘: begin = 0 for i in range(end, begin, -1): #range()函数,左闭右开 if s[i]>=‘0‘ and s[i]<=‘9‘: int_s[i] = s[i] else: return 0 if s[0] == ‘-‘: int_s[0] = ‘-‘ if s[0]==‘+‘: int_s = int_s[1:] return int(‘‘.join(int_s))