問題:
給定一個字符串,驗證其是否爲數字。
樣例:
樣例 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後出現