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.
class Solution { public: bool check(string& s,int start,int end,bool allowPoint,bool allowE){ if(start>end)return false; int i=start; bool point=allowPoint; if(s[i]=='+'||s[i]=='-'||s[i]>='0'&&s[i]<='9'||s[i]=='.'){ if(s[i]=='+'||s[i]=='-'){ i++; if(i>end)return false; if(s[i]>='0'&&s[i]<='9'){i++;} else if(s[i]=='.'){ if(!allowPoint)return false; i++; if(i>end)return false; if(s[i]>='0'&&s[i]<='9'){i++;} else{ return false; } } else return false; } else if(s[i]=='.'){ if(!allowPoint)return false; point=false; i++; if(i>end)return false; if(s[i]>='0'&&s[i]<='9'){i++;} else return false; } } else{ return false; } bool number=false; for(;i<=end;i++){ if(s[i]=='.'){ if(number)return false; if(!point)return false; else point=false; } else if(s[i]>='0'&&s[i]<='9'){ } else if(s[i]=='e'){ if(!allowE)return false; return check(s,i+1,end,false,false); } else { return false; } } return true; } bool isNumber(const char *s) { // Start typing your C/C++ solution below // DO NOT write int main() function if(s==NULL)return false; string ss(s); int start=0,end=ss.length()-1; while(ss[start]==' '&&start<ss.length()){ start++; } while(ss[end]==' '&&end>=0){ end--; } if(start>end)return false; return check(ss,start,end,true,true); } };