Valid Number
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 isNumber(string s) { int len = s.length(); int dotNum = 0; int eNum = 0; //去掉首位的空格 int start = len; for(int i=0;i<len;i++){ if(s[i] != ' '){ start = i; break; } } for(int i=len-1;i>=0;i--){ if(s[i] == ' '){ len--; }else{ break; } } if(start > len) return false; for(int i=start;i<len;i++){ if(s[i] >= '0' && s[i] <= '9'){ continue; }else if(s[i] == '.'){ if(dotNum > 0 || eNum >0 ) return false; dotNum++; if(i == start && i == len-1) return false; if(!(s[i-1] >= '0' && s[i-1] <= '9') && (i==len-1 || !(s[i+1] >= '0' && s[i+1] <= '9'))) return false; }else if(s[i] == 'e'){ if(eNum > 0) return false; eNum++; if(i==start) return false; if(s[i-1] == '-' || s[i-1] == '+') return false; if( i == len - 1) return false; }else if(s[i] == '-'){ if(i != start && s[i-1] != 'e') return false; if(i == len-1) return false; }else if(s[i] == '+'){ if(i != start && s[i-1] != 'e') return false; if(i==len-1) return false; }else{ return false; } } return true; } };