1 class Solution { 2 public: 3 bool isNumber(string s) { 4 if(s == " ") return false; 5 int i = 0; 6 int j = s.size()-1; 7 while(s[i] == ' ') ++i; 8 while(s[j] == ' ') --j; 9 ++j; 10 11 if(s[i] == '+' || s[i] == '-') ++i; 12 13 if(i == j) return false; 14 15 bool numberic = true; 16 bool flag = false; 17 18 int k = scanDigits(s,i,j); 19 if (k != i) 20 { 21 flag = true; 22 } 23 24 i = k; 25 26 if(i < j){ 27 if(s[i] == '.'){ 28 ++i; 29 if(i == j && !flag) return false; 30 else 31 { 32 k = scanDigits(s,i,j); 33 if (k != i) 34 { 35 flag = true; 36 } 37 i = k; 38 if(i < j && (s[i] == 'E'||s[i] == 'e')) 39 numberic = flag && isExponential(s, (++i),j); 40 } 41 42 } 43 else if(i < j && (s[i] == 'E'||s[i] == 'e')) 44 numberic = flag && isExponential(s, ++i,j); 45 else numberic = false; 46 } 47 48 return numberic && i == j; 49 50 } 51 52 int scanDigits(string str, int i,int j){ 53 while(i < j && str[i] >= '0'&& str[i] <= '9') ++i; 54 return i; 55 } 56 57 bool isExponential(string str, int& i, int j){ 58 if(i == j) return false; 59 if(str[i] == '+' || str[i] == '-') ++i; 60 61 if(i == j) return false; 62 i = scanDigits(str,i,j); 63 return i==j?true:false; 64 } 65 };
测试了好多次才过了 太不容易 所以贴个上来做下纪念
".9e1","+.1" "1."都正确