题目描述
解题思路
- 2e10不是十六进制数,是指数
- 如果含有e,以e为分隔符,前面是浮点数,后面是整数
- .1、1.均正确
import re
class Solution:
def isInt(self,s):
if not len(s):
return False
if s[0]=='+'or s[0]=='-':
s=s[1:]
#print(len(s))
if not len(s):
return True
if re.match('^[0-9]+$',s):
#print(s)
return True
else:
return False
def isInt2(self,s):
if not len(s):
return False
if s[0]=='+'or s[0]=='-':
s=s[1:]
if re.match('^[0-9]+$',s):
#print(s)
return True
else:
return False
def isFloat(self,s):
solution=Solution()
if not len(s):
return False
if '.' in s:
if s.count('.')>1:
return False
else:
[s1,s2]=s.split('.')
#print("s1:",s1,"s2:",s2)
if len(s1)==0 and len(s2)==0:
return False
elif len(s1)==0:
if s2[0].isdigit():
#print("here",s2[0])
return solution.isInt(s2)
else:
return False
elif len(s2)==0:
return solution.isInt(s1)
else:
if s2[0].isdigit():
return solution.isInt(s2) and solution.isInt(s1)
else:
return False
else:
return solution.isInt(s)
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
solution=Solution()
s=s.strip()
pattern=re.compile('[0-9]+')
if not pattern.findall(s):
return False
if not len(s):
return False
if 'e' in s:
eindex=s.index('e')
s1=s[:eindex]
if not len(s1):
return False
if s1[0]=='+'or s1[0]=='-':
s1=s1[1:]
s2=s[eindex+1:]
return solution.isFloat(s1) and solution.isInt2(s2)
else:
return solution.isFloat(s)
峰回路转
不断缝缝补补,终于涵盖了所有的情况,通过了甚是开心。然而
class Solution:
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
try:
float(s)
return True
except:
return False
哭晕哭晕
好吧~再写之前,还是应该好好思考