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.
Click to show spoilers.
Update (2014-12-06):
New test cases had been added. Thanks Unfounder ' s contribution.
Confirm that the input string is a numeric value, a series of judgments, mainly some positional judgments:
- Enter Front space
- PLUS sign
- Consecutive values, including '. '
- Symbol E
- PLUS sign
- Consecutive values, not including '. '
- Subsequent spaces
Follow the rules above.
#include <iostream>using namespacestd;classSolution { Public: BOOLIsnumber (Const Char*s) {intIDX =0; for(; s[idx]==' '; idx++); if(s[idx]=='-'|| s[idx]=='+') idx++; intPoint=0, num=0; for(;(s[idx]>='0'&&s[idx]<='9')|| s[idx]=='.'; idx++) S[idx]=='.'? point++:num++; if(point>1|| num<1)return false; if(s[idx]=='e') {idx++; if(s[idx]=='-'|| s[idx]=='+') idx++; Num=0; for(; s[idx]>='0'&&s[idx]<='9'; idx++) num++; if(num<1)return false; } for(; s[idx]==' '; idx++); returns[idx]==' /'; }};intMain () {Chara[]="-e-"; Solution Sol; cout<<sol.isnumber (a) <<Endl; return 0;}
[Leetcode] Valid number to confirm whether it is a numeric value