# 有效数字
有效数字(按顺序)可以分成以下几个部分:
- 一个 小数 或者 整数
- (可选)一个
'e'
或 'E'
,后面跟着一个 整数
小数(按顺序)可以分成以下几个部分:
- (可选)一个符号字符(
'+'
或 '-'
) - 下述格式之一:
- 至少一位数字,后面跟着一个点
'.'
- 至少一位数字,后面跟着一个点
'.'
,后面再跟着至少一位数字 - 一个点
'.'
,后面跟着至少一位数字
整数(按顺序)可以分成以下几个部分:
- (可选)一个符号字符(
'+'
或 '-'
) - 至少一位数字
部分有效数字列举如下:
["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"]
部分无效数字列举如下:
["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"]
给你一个字符串 s
,如果 s
是一个 有效数字 ,请返回 true
。
示例 1:
输入:s = "0"
输出:true
示例 2:
输入:s = "e"
输出:false
示例 3:
输入:s = "."
输出:false
示例 4:
输入:s = ".1"
输出:true
提示:
1 <= s.length <= 20
s
仅含英文字母(大写和小写),数字(0-9
),加号 '+'
,减号 '-'
,或者点 '.'
。
以下程序实现了这一功能,请你填补空白处内容:
```python
class Solution(object):
def isNumber(self, s):
s = s.strip()
ls, pos = len(s), 0
if ls == 0:
return False
if s[pos] == '+' or s[pos] == '-':
pos += 1
isNumeric = False
while pos < ls and s[pos].isdigit():
pos += 1
isNumeric = True
_____________________________;
elif pos < ls and s[pos] == 'e' and isNumeric:
isNumeric = False
pos += 1
if pos < ls and (s[pos] == '+' or s[pos] == '-'):
pos += 1
while pos < ls and s[pos].isdigit():
pos += 1
isNumeric = True
if pos == ls and isNumeric:
return True
return False
# %%
s = Solution()
print(s.isNumber(s = "0"))
```
## template
```python
class Solution(object):
def isNumber(self, s):
s = s.strip()
ls, pos = len(s), 0
if ls == 0:
return False
if s[pos] == '+' or s[pos] == '-':
pos += 1
isNumeric = False
while pos < ls and s[pos].isdigit():
pos += 1
isNumeric = True
if pos < ls and s[pos] == '.':
pos += 1
while pos < ls and s[pos].isdigit():
pos += 1
isNumeric = True
elif pos < ls and s[pos] == 'e' and isNumeric:
isNumeric = False
pos += 1
if pos < ls and (s[pos] == '+' or s[pos] == '-'):
pos += 1
while pos < ls and s[pos].isdigit():
pos += 1
isNumeric = True
if pos == ls and isNumeric:
return True
return False
# %%
s = Solution()
print(s.isNumber(s = "0"))
```
## 答案
```python
if pos < ls and s[pos] == '.':
pos += 1
while pos < ls and s[pos].isdigit():
pos += 1
isNumeric = True
```
## 选项
### A
```python
if pos < ls and s[pos] == '.':
pos += 1
while pos < ls:
pos += 1
isNumeric = True
```
### B
```python
if pos < ls and s[pos] == '.':
pos += 1
while pos > ls:
pos += 1
isNumeric = True
```
### C
```python
if pos < ls and s[pos] == '.':
pos += 1
while pos > ls and s[pos].isdigit():
pos += 1
isNumeric = True
```