问题:
给定一个字符串,验证其是否为数字。
样例:
样例 1:
输入: "0" 输出: true 解释: "0" 可以被转换成 0
样例 2:
输入: "0.1" 输出: true 解释: "0.1" 可以被转换成 0.1
样例 3:
输入: "abc" 输出: false
样例 4:
输入: "1 a" 输出: false
样例 5:
输入: "2e10" 输出: true 解释: "2e10" 代表 20,000,000,000
python:
class Solution:
"""
@param s: the string that represents a number
@return: whether the string is a valid number
"""
def isNumber(self, s):
# write your code here
if s == None:
return False
start = 0
end = len(s)-1
while start < end and s[start] == ' ':
start += 1
while end > start and s[end] == ' ':
end -= 1
if s[start] == '+' or s[end] == '-':
start += 1
if start > end:
return False
isNum = False
isExp = False
isDot = False
while start <= end:
if s[start].isdecimal():
isNum = True
elif s[start] == 'e':
if isExp or not isNum:
return False
isExp = True
isNum = False
elif s[start] == '.':
if isDot or isExp:
return False
isDot = True
elif s[start] == '+' or s[start] == '-':
if s[start-1] != 'e':
return False
else:
return False
start += 1
return isNum
C++:
class Solution {
public:
/**
* @param s: the string that represents a number
* @return: whether the string is a valid number
*/
bool isNumber(string &s) {
// write your code here
if(s == "")
{
return false;
}
int start = 0;
int end = s.size()-1;
while(start < end && s[start] == ' ')
{
start++;
}
while(end > start && s[end] == ' ')
{
end--;
}
if(s[start] == '+' || s[start] == '-')
{
start++;
}
if (start > end)
{
return false;
}
bool isNum = false;
bool isExp = false;
bool isDot = false;
while(start <= end)
{
if(int(s[start] - '0') >= 0 && int(s[start] - '9') <= 0)
{
isNum = true;
}else if(int(s[start] - 'e') == 0)
{
if(isExp || !isNum)
{
return false;
}
isExp = true;
isNum = false;
}else if(int(s[start] - '.') == 0)
{
if(isDot || isExp)
{
return false;
}
isDot = true;
}else if(int(s[start] - '+') == 0 || int(s[start] - '-') == 0)
{
if(int(s[start-1] - 'e') != 0)
{
return false;
}
}else{
return false;
}
start++;
}
return isNum;
}
};
PS:规则不太好理解。。。
PS:前后去空,正负检测,2个e直接返回,点不能出现在e所有后面,加减号只能紧接着e后出现