1Valid Number
Validate if a given string is numeric.
Some examples:"0"
=> true
" 0.1 "
=> true
"abc"
=> false
"1 a"
=> false
"2e10"
=> true
class Solution { public: inline bool isDg(char c){ return c>='0'&&c<='9'; } bool isNumber(const char *s) { int i=0; while(s[i]==' '){ i++; } //状态标识 first=i; hasDot=false,hasE=false,hasDg=false; while(s[i]!=0){ //while式从左到右线性状态机 if(s[i]=='-'||s[i]=='+') { if(i!=first) return false; else i++; //first==i, 一个基本数(不含e)的开始可以是+/- } while(isDg(s[i])) hasDg=true,i++; switch(s[i]){ case 'e': if(hasE||!hasDg) return false; hasE=true; first=i+1; hasDot=hasDg=false; break; case '.': if(hasE||hasDot) return false; hasDot=true; break; case 0: return hasDg; /*注意不要break;否则跳出switch执行i++, 但不会跳出while,导致数组越界*/ case ' ': while(s[i]!=0){ //结尾的空格 if(s[i]!=' ') return false; i++; } return hasDg; default: //非法字符 return false; } i++; } return hasDg; } };