题目分析:
这一题让我们判断一个数是否可转换为数字,开始直接调用python转换为float的函数 + 异常返回(见附),虽然通过了但感觉很过分。这题的本意应该是让我们分为很多情况逐位经过多个判断,我参考了[LeetCode] Valid Number 验证数字,我只是把他的代码转为了python版本,原作者的解析写的非常到位,不再繁叙。
测试代码:
#submit
class Solution:
def isNumber(self, s: str) -> bool:
num = False; numAfterE = True; dot = False; exp = False; sign = False; length =len(s)
for i in range(length):
if s[i] == ' ':
if i < length - 1 and s[i + 1] != ' ' and (num or dot or exp or sign): return False
elif s[i] in {'+', '-'}:
if i > 0 and s[i - 1] not in {' ', 'e'}: return False
sign = True
elif s[i] >= '0' and s[i] <= '9':
num = True
numAfterE = True
elif s[i] == '.':
if dot or exp: return False
dot = True
elif s[i] == 'e':
if exp or not num: return False
exp = True
numAfterE = False
else: return False
return num and numAfterE
print(Solution().isNumber(" 005047e+6")) #提交时请删除该行
附:(调用转换为float + 异常处理的代码)
class Solution:
def isNumber(self, s: str) -> bool:
try:
float(s)
return True
except:
return False