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.
思路:
需要注意的地方:
1、其实的空格
2、e的次数,以及e前后都要有数字
3、小数点的次数,以及小数点不能前后都没有数字
4、开始和e之后可以有'+''-'
代码:
1 bool isNumber(const char *s) { 2 while(*s == ' ') 3 s++; 4 if(*s == '+' || *s == '-') 5 s++; 6 int l = strlen(s); 7 if(l == 0) 8 return false; 9 int eNum = 0, pointNum = 0; 10 bool beforeE = false, beforePoint = false, afterE = false, afterPoint = false; 11 int i; 12 for(i = 0; i < l; i++){ 13 if(s[i] >= '0' && s[i] <= '9'){ 14 if(eNum == 0) 15 beforeE = true; 16 else 17 afterE = true; 18 if(pointNum == 0) 19 beforePoint = true; 20 else 21 afterPoint = true; 22 continue; 23 } 24 else if(s[i] == 'e'){ 25 if(eNum == 0){ 26 eNum++; 27 if(s[i+1] == '+' || s[i+1] == '-') 28 i++; 29 } 30 else 31 return false; 32 } 33 else if(s[i] == '.'){ 34 if(pointNum > 0 || eNum > 0) 35 return false; 36 pointNum++; 37 } 38 else if(s[i] == ' '){ 39 while(s[i] == ' ') 40 i++; 41 if(s[i] != '\0') 42 return false; 43 else 44 break; 45 } 46 else 47 return false; 48 } 49 if(eNum == 1 && !(beforeE && afterE)) 50 return false; 51 if(pointNum == 1 && !afterPoint && !beforePoint) 52 return false; 53 return true; 54 }