Validate if a given string can be interpreted as a decimal number.
Some examples: "0" => true " 0.1 " => true "abc" => false "1 a" => false "2e10" => true " -90e3 " => true " 1e" => false "e3" => false " 6e-1" => true " 99e2.5 " => false "53.5e93" => true " --6 " => false "-+3" => false "95a54e53" => false
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number:
Numbers 0-9 Exponent - "e" Positive/negative sign - "+"/"-" Decimal point - "."
My code:
class Solution:
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
#First remove the space
#Check if there are space in the middle, if so, return False
check_mark=False
count_index=-1
for i in range(len(s)):
if not check_mark and s[i]!=' ':
check_mark=True
continue
if check_mark and s[i]==' ':
for k in range(i,len(s)):
if s[k]!=' ':
return False
s=s.replace(" ","")
#Then we need to check if it includes string that is not in our required text
tmp_list=set(['0','1','2','3','4','5','6','7','8','9','.','e','-','+'])
#record the . count
count=0
for i in range(len(s)):
if s[i] not in tmp_list:
return False
if s[i]=='.':
count+=1
if count>1:
return False
#Check the valid of e.
checkFlag=False
for i in range(len(s)):
if s[i]=='e' and not checkFlag:
if i==0:
return False
tmp_str=s[:i]
try:
tmp=float(tmp_str)
except:
return False#no valid part before
checkFlag=True
tmp_str=s[i+1:]
try:
tmp=float(tmp_str)
except:
return False#no valid part before
continue
if checkFlag and s[i]=='.':
return False
if checkFlag and s[i]=='e':
return False
#print('last check')
#Check the valid of the + and -
check_flag=False
for i in range(len(s)):
if not check_flag and (s[i]=='+' or s[i]=='-'):
if i==0:
check_flag=True
continue
if s[i-1]=='e':
check_flag=True
continue
return False
if s[i]=='e':
check_flag=False
if check_flag and (s[i]=='+' or s[i]=='-'):
return False
#Check if there exist a number value, if not false
tmp_list=set(['0','1','2','3','4','5','6','7','8','9'])
mark=True
for i in range(len(s)):
if s[i] in tmp_list:
mark=False
break
if mark:
return False
return True
My code2:
class Solution:
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
#First remove the space
#Check if there are space in the middle, if so, return False
check_mark=False
count_index=-1
for i in range(len(s)):
if not check_mark and s[i]!=' ':
check_mark=True
continue
if check_mark and s[i]==' ':
for k in range(i,len(s)):
if s[k]!=' ':
return False
s=s.replace(" ","")
try:
tmp=float(s)
except:
return False
return True