Topic
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.
Update (2015-02-10):
The signature of the C + + function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your cod E definition.
Ideas
No
Code
/ *---------------------------------------* Date: 2015-06-16* sjf0115* title: 65.Valid number* Website: https://leetcode.co m/problems/valid-number/* Result: ac* Source: leetcode* Blog:-----------------------------------------*/#include <iostream>#include <cstdio>using namespace STD;classSolution { Public:BOOLIsnumber (strings) {intSize = S.size ();if(Size = =0){return false; }//if //Preamble 0 intStart =0; while(S[start] = ="') {++start; }//while //rear guide 0 intend = Size-1; while(S[end] = ="') {--end; }//while BOOLHasnum =false, Haspoint =false, HasE =false; for(inti = Start;i <= end;++i) {if(S[i] = ='. '){//If you already have '. ' or ' e ' in front of you if(Haspoint | | hasE) {return false; }//ifHaspoint =true; }//if Else if(S[i] = =' E '){//If there are ' e ' or no numbers in front if(HasE | |!hasnum) {return false; }//ifHasE =true; }//else Else if(S[i] <' 0 '|| S[i] >' 9 '){//+2 if(i = = Start && (s[i] = =' + '|| S[i] = ='-')){Continue; }//if //1e-2 Else if((I! =0&& s[i-1] ==' E ') && (s[i] = =' + '|| S[i] = ='-')){Continue; }Else{return false; }//else}//else Else{Hasnum =true; }//else}//for ///Last effective bit cannot be ' e+-' if(S[end] = =' E '|| S[end] = =' + '|| S[end] = ='-'){return false; }//if //'. ' if(!hasnum && Haspoint) {return false; }//if //Full of spaces if(End = =-1){return false; }//if return true; }};intMain () {solution S;stringStr"4.4e3");//char* str = ". 3e4"; cout<<s.isnumber (str) <<endl;return 0;}
Run time
Test Cases
That's right:
.3
3.
3.3
4e4
46.e3
4.3e3
.4e4
Error:
E
.
4e
E4
. e4
45e.2
[Leetcode]65.valid number