Validate if a given string is numeric.
Some examples:
"0"
=>true
" 0.1 "
=>true
"abc"
=>false
"1 a"
=>false
"2e10"
=>true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
这首题的难度为difficult,说难也不难,可是难就在于,怎样判断它是否输入为数字串,需要考虑的输入除了题目给出的几种,还有" 12 ", "-1.2 ",“+.1”,“ e0”......
此时,我们应该分析一下,对于所有的输入类型,进行一个非数字串的错误分析,如果分析不清楚,就有可能落掉情况或者代码冗长。
首先,我们把能够出现在字符中的内容分为以下六类:空格、数字、+ (-)号、小数点、e、其它。这几种类型有不是在字符串的每个位置都可以出现的,有些只能出现在特定的位置。
例如:
- 空格可以出现在首尾;
- + (-)号只能出现在除空格的第一个位置或者e的后面;
- .的后面必须有数字,它的前面可以有数字或者是+(-)符号;
- e的前面和后面必须有数字;
其次,为了不落掉任何一个位置上的信息,我们可以从头到尾来分析每个位置上的元素(遇到确定非数字串的情况就结束),来判断错误的输入;
代码如下:
class Solution {
private:
bool isSpace(char c){ return c==' ';}
bool isSgn(char c){ return c=='+'||c=='-';}
bool isDot(char c){ return c=='.';}
bool isNum(char c){ return c<='9'&&c>='0';}
bool isE(char c){ return c=='e'||c=='E';}
public:
bool isNumber(string s) {
int pos=0;
bool haveNum = false;
// Check all the prefix spaces
while ( pos<s.size() && isSpace(s[pos]) ) pos++;
// Check the next char if it's a +/- signal
if ( pos<s.size() && isSgn(s[pos]) ) pos++;
// Check the numbers before a dot '.'
while ( pos<s.size() && isNum(s[pos]) ) {haveNum = true; pos++;}
// Check the dot '.'
if ( pos<s.size() && isDot(s[pos]) ) pos++;
// Check the numbers after a dot '.'
while ( pos<s.size() && isNum(s[pos]) ) {haveNum = true; pos++;}
// Check the 'e' / 'E'
if ( haveNum && pos<s.size() && isE(s[pos]) ) {
haveNum = false; pos++;
if ( pos<s.size() && isSgn(s[pos]) ) pos++;
}
// Check the numbers after 'e' / 'E'
while ( pos<s.size() && isNum(s[pos]) ) {haveNum = true; pos++;}
// Check all the remaining spaces
while ( pos<s.size() && isSpace(s[pos]) ) pos++;
// Everything is done, if the string not empty, return false.
return ( pos==s.size() && haveNum );
}
};