Description:
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.
分析:
方法一:
网上看到的一个大神利用自动机理论
http://noalgo.info/995.html
代码:
#include <iostream>
using namespace std;
bool isNumber(const char *s) {
enum InputType {
INVALID, SPACE, SIGN, DOT, E, DIGIT, LEN
};
int trans[][LEN] = {
{-1, 0, 1, 2, -1, 3},
{-1, -1, -1, 2, -1, 3},
{-1, -1, -1, -1, -1, 4},
{-1, 5, -1, 4, 6, 3},
{-1, 5, -1, -1, 6, 4},
{-1, 5, -1, -1, -1, -1},
{-1, -1, 7, -1, -1, 8},
{-1, -1, -1, -1, -1, 8},
{-1, 5, -1, -1, -1, 8}
};
int state = 0;
while (*s) {
InputType input;
if (isspace(*s)) {
input = SPACE;
} else if (*s == '+' || *s == '-') {
input = SIGN;
} else if (*s == '.') {
input = DOT;
} else if (*s == 'e' || *s == 'E') {
input = E;
} else if (isdigit(*s)) {
input = DIGIT;
} else {
input = INVALID;
}
state = trans[state][input];
if (state == -1) {
return false;
}
s++;
}
return state == 3 || state == 4 || state == 5 || state == 8;
}
int main(int argc, char const *argv[]) {
// “0″ => true
// ” 0.1 ” => true
// “abc” => false
// “1 a” => false
// “2e10″ => true
const char *s1 = "0";
const char *s2 = " 0.1";
const char *s3 = "abc";
const char *s4 = "1 a";
const char *s5 = "2e10";
cout<<boolalpha<<isNumber(s1)<<endl;
cout<<boolalpha<<isNumber(s2)<<endl;
cout<<boolalpha<<isNumber(s3)<<endl;
cout<<boolalpha<<isNumber(s4)<<endl;
cout<<boolalpha<<isNumber(s5)<<endl;
return 0;
}
测试:
方法二:利用标准库strtod函数
strtod()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,到出现非数字或字符串结束时(‘\0’)才结束转换,并将结果返回。若endptr不为NULL,则会将遇到不合条件而终止的nptr中的字符指针由endptr传回。参数nptr字符串可包含正负号、小数点或E(e)来表示指数部分。如123.456或123e-2。
代码:
#include <iostream>
#include <cstdlib>
using namespace std;
bool isNumber(const char *s) {
char *endptr;
strtod(s, &endptr);
if (endptr == s)
return false;
while (*endptr) {
if(!isspace(*endptr))
return false;
endptr++;
}
return true;
}
int main(int argc, char const *argv[]) {
// “0″ => true
// ” 0.1 ” => true
// “abc” => false
// “1 a” => false
// “2e10″ => true
const char *s1 = "0";
const char *s2 = " 0.1";
const char *s3 = "abc";
const char *s4 = "1 a";
const char *s5 = "2e10";
cout<<boolalpha<<isNumber(s1)<<endl;
cout<<boolalpha<<isNumber(s2)<<endl;
cout<<boolalpha<<isNumber(s3)<<endl;
cout<<boolalpha<<isNumber(s4)<<endl;
cout<<boolalpha<<isNumber(s5)<<endl;
return 0;
}
测试: