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.
这道题写的好麻烦啊,一些很奇怪的case也被认为是正确的
注意事项:
1. 前后空格
2. "+","-"号
3. "e"和"E"的出现位置
4."."小数点的出现位置
5. "1.", ".34","+.1"也被认为是正确的
1 class Solution { 2 public: 3 bool isNumber(const char *s) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 if(s==NULL) 7 return false; 8 int i=0; 9 int j=strlen(s)-1; 10 while(s[i]==' ') i++; 11 while(j>=0 && s[j]==' ') j--; 12 if(i>j) 13 return false; 14 string str(s+i,j-i+1); 15 int e; 16 bool hasE = false; 17 for(int i=0;i<str.length();i++) 18 if(str[i]=='e' || str[i]=='E'){ 19 if(hasE) 20 return false; 21 else{ 22 hasE=true; 23 e=i; 24 } 25 } 26 if(hasE){ 27 string str1(str.begin(),str.begin()+e); 28 string str2(str.begin()+e+1,str.end()); 29 return isNumberWithoutE(str1) && isSignNumber(str2); 30 } 31 return isNumberWithoutE(str); 32 } 33 34 bool isNumberWithoutE(string s){ 35 if(s.length()==0) 36 return false; 37 if(s[0]=='+' || s[0]=='-') 38 s = string(s.begin()+1,s.end()); 39 if(s.length()==0) 40 return false; 41 int dot; 42 bool hasDot = false; 43 for(int i=0;i<s.length();i++){ 44 if(s[i]=='.'){ 45 if(hasDot) 46 return false; 47 else{ 48 hasDot=true; 49 dot=i; 50 } 51 } 52 } 53 54 if(hasDot){ 55 string str1(s.begin(),s.begin()+dot); 56 string str2(s.begin()+dot+1,s.end()); 57 if(str1.length()==0 && str2.length()==0) 58 return false; 59 if(str1.length()==0) 60 return isPureNumber(str2); 61 if(str2.length()==0) 62 return isPureNumber(str1); 63 return isPureNumber(str1) && isPureNumber(str2); 64 } 65 66 return isPureNumber(s); 67 } 68 69 bool isSignNumber(string s){ 70 if(s.length()==0) 71 return false; 72 if(s[0]=='+' || s[0]=='-') 73 s = string(s.begin()+1,s.end()); 74 return isPureNumber(s); 75 } 76 77 bool isPureNumber(string s){ 78 if(s.length()==0) 79 return false; 80 for(int i=0;i<s.length();i++) 81 if(s[i]<'0' || s[i]>'9') 82 return false; 83 return true; 84 } 85 };