标签:
Validate if a given string is numeric.
Some examples:"0"
=> true
" 0.1 "
=> true
"abc"
=> false
"1 a"
=> false
"2e10"
=> true
1 #include <string.h> 2 #include <iostream> 3 #include <ctype.h> 4 5 #include <fstream> 6 7 using namespace std; 8 9 class Solution 10 { 11 public: 12 bool isNumber(const char *s) 13 { 14 bool has_front_num = false, has_back_num = false, has_e = false; 15 int len = strlen(s); 16 int i = 0; 17 18 while(i < len && ‘ ‘ == s[i]) 19 i++; 20 21 if(i == len) return false; 22 23 if(i < len && (s[i] == ‘+‘ || s[i] == ‘-‘)) 24 i++; 25 26 while(i < len && isdigit(s[i])) 27 { 28 i++; 29 has_front_num = true; 30 } 31 32 if(i < len && s[i] == ‘.‘) 33 i++; 34 35 while(i < len && isdigit(s[i])) 36 { 37 i++; 38 has_front_num = true; 39 } 40 41 if(i < len && (s[i] == ‘e‘ || s[i] == ‘E‘) && has_front_num) 42 { 43 i++; 44 has_e = true; 45 if(i == len) return false; 46 } 47 48 49 if(i < len && (s[i] == ‘+‘ || s[i] == ‘-‘) && has_e) 50 i++; 51 52 while(i < len && isdigit(s[i]) && has_e) 53 { 54 i++; 55 has_back_num = true; 56 } 57 58 while(i < len && s[i] == ‘ ‘) 59 i++; 60 61 if(i == len && has_e && has_back_num) 62 return true; 63 else if(i == len && !has_back_num && !has_e && has_front_num) 64 return true; 65 66 return false; 67 } 68 }; 69 70 int main() 71 { 72 ifstream cin("aa"); 73 Solution s; 74 char *ss; 75 while(cin >> ss) 76 cout << s.isNumber(ss) << endl; 77 return 0; 78 }
标签:
原文地址:http://www.cnblogs.com/lxd2502/p/4245538.html