(在队友怂恿下写了LeetCode上的一个水题)
题意
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.
Solution
题意是判断一个串是不是合法的实数(double literal),实际上是想让你实现 istream::istream &operator>>(const double &)(针对C++而言)。
我们当然可以 hand-code 出这个函数,但是更好的做法的利用 istream 类的某些 flag(member function)以其人之道还治其人之身。
Implementation
class Solution {
public:
bool isNumber(string s) {
int b=, e=s.size();
for(; isspace(s[b]); b++);
for(; isspace(s[e-]); e--);
string t=s.substr(b, e-b);
if(*t.rbegin()!='.'&&!isdigit(*t.rbegin())) return false;
if(*t.rbegin()=='.'&&!isdigit(*(t.rbegin()+))) return false;
stringstream x(t);
double y;
x>>y;
return x.eof();
}
};
这大概是目前为止最短的C++实现了(如果不用regular expression的话)。。。(逃)
如果C++中double的范围充分大,还可以实现得更短:
class Solution {
public:
bool isNumber(string s) {
int b=, e=s.size();
for(; isspace(s[b]); b++);
for(; isspace(s[e-]); e--);
stringstream x(s.substr(b, e-b));
double y;
x>>y;
return !x.fail() && x.eof();
}
};