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.
再加几个测试用例:
"1." => true
".3" => true
"." => false
"1e+10" =>true
"1e0.6" =>false
"1e" => false
"e1" => false
"e" => false
" 1 " => true
1 class Solution { 2 public: 3 bool isNumber(const char *s) { 4 while (*s != ‘\0‘ && *s == ‘ ‘) s++; // 左侧空白 5 6 int n = strlen(s); 7 if (n == 0) return false; // 空串 8 9 // 正负号 10 if (s[0] == ‘+‘ || s[0] == ‘-‘) { 11 s++; 12 } 13 14 15 int e = 0, dot = 0; 16 int elnum = 0, ernum = 0, num = 0, dlnum = 0, drnum = 0; 17 while (*s != ‘\0‘) { 18 if (*s < ‘0‘ || *s > ‘9‘) { 19 if (*s == ‘e‘ || *s == ‘E‘) { 20 e++; 21 if (e == 1 && *(s + 1) != ‘\0‘ && (*(s + 1) == ‘-‘ || *(s + 1) == ‘+‘)) { //1e-10, 1e+10,e的后面允许有一个符号 22 s++; 23 } 24 if (e > 1) return false; // 只能有一个e. 1e10, 1e-10 25 } else if (*s == ‘.‘) { 26 dot++; 27 if (dot > 1) return false; // 只能有一个小数点 28 if (e == 1) return false; // 如果在e的后面,不允许有小数点 29 30 } else { 31 break; // 其他字符不合法 32 } 33 } else { 34 num++; 35 if (e == 0) elnum++; //统计e左右的数字个数 36 else ernum++; 37 38 if (dot == 0) dlnum++; //统计小数点左右的数字个数 39 else drnum++; 40 } 41 s++; 42 } 43 if (e == 1 && (elnum ==0 || ernum == 0)) return false; // 如果e的左或右没有数字 e10, 1e不合法 44 if (dot == 1 && dlnum == 0 && drnum == 0) return false; // 如果小数点左右都没有数字,1. 合法,.3合法,但是.不合法。 45 46 while (*s != ‘\0‘ && *s == ‘ ‘) s++; //忽略右边空格 47 if (*s != ‘\0‘) return false; // 如果右边空格之后还有字符,比如"1e10 a" 48 49 return num > 0; 50 } 51 };
LeetCode | Valid Number,布布扣,bubuko.com
原文:http://www.cnblogs.com/linyx/p/3656091.html