标签:
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 class Solution { 2 public: 3 4 enum TYPE 5 { 6 INVALID, 7 SPACE, 8 SIGN, 9 DIGIT, 10 DOT, 11 EXP 12 }; 13 14 bool isNumber(const char *s) { 15 16 while(*s!=‘\0‘&&*s==‘ ‘) s++; 17 if(*s==‘+‘||*s==‘-‘) s++; 18 19 20 if(strlen(s)==0) return false; 21 22 bool hasSign=false; 23 bool hasDigit=false; 24 bool hasDot=false; 25 bool hasExp=false; 26 27 TYPE preType; 28 TYPE type; 29 while(*s!=‘\0‘) 30 { 31 type=getType(s); 32 33 if(type==INVALID) return false; 34 35 if(preType==SIGN &&(type!=DIGIT&&type!=DOT)) return false; 36 if(preType==DOT&&(type!=DIGIT&&type!=SPACE&&type!=EXP))return false; 37 if(preType==EXP&&(type!=DIGIT&&type!=SIGN))return false; 38 if(preType==SPACE&&type!=SPACE)return false; 39 40 41 switch(type) 42 { 43 case SPACE: 44 preType=SPACE; 45 break; 46 case SIGN: 47 if(hasSign) return false; 48 else 49 { 50 if(preType!=EXP) return false; 51 hasSign=true; 52 preType=SIGN; 53 } 54 break; 55 case DIGIT: 56 hasDigit=true; 57 preType=DIGIT; 58 break; 59 case DOT: 60 if(hasDot||hasExp) return false; 61 else 62 { 63 hasDot=true; 64 preType=DOT; 65 } 66 break; 67 case EXP: 68 if(hasExp||!hasDigit) return false; 69 else 70 { 71 hasExp=true; 72 preType=EXP; 73 } 74 break; 75 } 76 s++; 77 } 78 79 if(preType==SIGN||preType==EXP||(!hasDigit&&hasDot)) return false; 80 81 return true; 82 } 83 84 85 TYPE getType(const char *s) 86 { 87 if(*s==‘ ‘) return SPACE; 88 else if(*s==‘+‘||*s==‘-‘) return SIGN; 89 else if(isdigit(*s))return DIGIT; 90 else if(*s==‘.‘)return DOT; 91 else if(*s==‘e‘)return EXP; 92 else return INVALID; 93 } 94 };
标签:
原文地址:http://www.cnblogs.com/reachteam/p/4237508.html