【题目描述】
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100",“5e2”,"-123",“3.1416"和”-1E-16"都表示数值。 但是"12e",“1a3.14”,“1.2.3”,"±5"和"12e+4.3"都不是。
【解题思路】
考虑有数字中带有e的和不带有e的。
对于不带有e的数字,判断其是否合法的标准是,是否有超过一个小数点,如果有正负号的话正负号的位置只能在第一个位置,是否有其它字符
对于带有e的数字,分两部分判断它,e之前的部分与不带有e的数字的判断标准相同;e之后的部分不能有小数点,如果出现正负号的话正负号只能在e之后的第一个位置,是否有其它字符。
用Python实现的代码如下:
# -*- coding:utf-8 -*-
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
pos = 0
point_num, flag_num = 0,0
while pos < len(s):
if s[pos] == '.':
point_num += 1
if point_num > 1:
return False
pos += 1
elif s[pos] == '+' or s[pos] == '-':
flag_num += 1
if flag_num > 1 or pos > 0:
return False
pos += 1
elif s[pos] >= '0' and s[pos] <= '9':
pos += 1
elif s[pos] == 'E' or s[pos] == 'e':
pos += 1
if pos == len(s):
return False
if s[pos]=='+' or s[pos] == '-':
pos += 1
if pos == len(s):
return False
tag = 0
while pos < len(s):
if s[pos] >= '0' and s[pos] <= '9':
tag = 1
pos += 1
else:
return False
if tag == 1:
return True
elif s[pos] >= '0' and s[pos] <= '9':
tag = 0
while pos < len(s):
if s[pos] >= '0' and s[pos] <= '9':
tag = 1
pos += 1
else:
return False
if tag == 1:
return True
else:
return False
else:
return False
return True