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.
The subject needs to be considered:
1, the space before the character
2. Character sign
3, check whether it is a number, the number can contain a '. ' Decimal point, the number should have at least one
4, after the number and point, check if there is ' e ', if there is:
(1) Check whether the index is positive or negative
(2) Check if there is a number, there is at least one
5, the space after the character
6. The last encounter ' \ ' returns true, otherwise false
Code:
1 classSolution {2 Public:3 BOOLIsnumber (strings) {4 inti =0;5 6 //Skip the Whilespaces7 for(; s[i] = =' '; i++) {}8 9 //Check the significandTen if(S[i] = ='+'|| S[i] = ='-') i++;//Skip the sign if exist One A intn_nm, n_pt; - for(n_nm=0, n_pt=0; (s[i]<='9'&& s[i]>='0') || s[i]=='.'; i++) -S[i] = ='.'? n_pt++:n_nm++; the if(n_pt>1|| n_nm<1)//no more than one point, at least one digit - return false; - - //Check the exponent if exist + if(S[i] = ='e') { -i++; + if(S[i] = ='+'|| S[i] = ='-') i++;//Skip The Sign A at intN_NM =0; - for(; s[i]>='0'&& s[i]<='9'; i++, n_nm++) {} - if(n_nm<1) - return false; - } - in //Skip the trailing whitespaces - for(; s[i] = =' '; i++) {} to + returns[i]==0;//must reach the ending 0 of the string - } the};
"Leetcode" "Hard" Valid number