LeetCode 65 Valid Number
(在队友怂恿下写了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
1 class Solution { 2 public: 3 bool isNumber(string s) { 4 int b=0, e=s.size(); 5 for(; isspace(s[b]); b++); 6 for(; isspace(s[e-1]); e--); 7 string t=s.substr(b, e-b); 8 if(*t.rbegin()!='.'&&!isdigit(*t.rbegin())) return false; 9 if(*t.rbegin()=='.'&&!isdigit(*(t.rbegin()+1))) return false; 10 stringstream x(t); 11 double y; 12 x>>y; 13 return x.eof(); 14 } 15 };
这大概是目前为止最短的C++实现了(如果不用regular expression的话)。。。(逃)
如果C++中double的范围充分大,还可以实现得更短:
1 class Solution { 2 public: 3 bool isNumber(string s) { 4 int b=0, e=s.size(); 5 for(; isspace(s[b]); b++); 6 for(; isspace(s[e-1]); e--); 7 stringstream x(s.substr(b, e-b)); 8 double y; 9 x>>y; 10 return !x.fail() && x.eof(); 11 } 12 };