(I wrote a water question on leetcode with my teammates)
Portal
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:
Test instructions is to judge if a string is not a valid real number (double literal) and actually wants you to implement Istream::istream &operator>> (const double &)(for C + +).
We can certainly hand-code out this function, but it is better to use some flag (member function) dose his own medicine of the IStream class.
Implementation:
1 classSolution {2 Public:3 BOOLIsnumber (strings) {4 intb=0, e=s.size ();5 for(; Isspace (S[b]); b++);6 for(; Isspace (s[e-1]); e--);7 stringT=s.substr (b, E-b);8 if(*t.rbegin ()! ='.'&&!isdigit (*t.rbegin ()))return false;9 if(*t.rbegin () = ='.'&&!isdigit (* (T.rbegin () +1)))return false; Ten StringStream x (t); One Doubley; AX>>y; - returnx.eof (); - } the};
This is probably by far the shortest C + + implementation (if not regular expression) ... Escape
If the range of double in C + + is sufficiently large, it can be achieved even shorter:
1 classSolution {2 Public:3 BOOLIsnumber (strings) {4 intb=0, e=s.size ();5 for(; Isspace (S[b]); b++);6 for(; Isspace (s[e-1]); e--);7StringStream x (s.substr (b, Eb));8 Doubley;9X>>y;Ten return!x.fail () &&x.eof (); One } A};
Leetcode Valid Number