Validate if a given string is numeric.git
Some examples:"0"
=> true
" 0.1 "
=> true
"abc"
=> false
"1 a"
=> false
"2e10"
=> true
ui
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.spa
思路:本題須要討論四種狀況——數字、e、'.'、正負號.code
正負號:只出如今第一個字符或e的後面一個字符;blog
小數點:字符串中不能只存在小數點,也不能只含小數點和正負號,小數點不能在e後rem
e:不能出如今第一個字符或最後一個字符,e前面不能沒有數字。字符串
在處理以前,先把頭尾的空格去掉,而後在進行數字、e、'.'、正負號的判斷。string
class Solution { public: bool isNumber(const char *s) { if(strlen(s)<=0) return true; while(*s==' ') s++; const char *pEnd=s+strlen(s)-1; while(*pEnd==' ') pEnd--; if(*s=='+'||*s=='-') s++; const char *pBeg=s; int digit=0; int point=0; int e=0; while(*pBeg!='\0'&&pBeg<=pEnd) { if(isdigit(*pBeg)) { pBeg++; digit++; } else if(*pBeg=='.'&&e==0) { pBeg++; point++; } else if(*pBeg=='e'&&pBeg!=s&&digit>=1) { if(isdigit(*(pBeg+1))) { pBeg=pBeg+2; e++; } else if((pBeg+2<=pEnd)&&(*(pBeg+1)=='+'||*(pBeg+1)=='-')) { pBeg=pBeg+2; e++; } else return false; } else return false; } if(digit>=1&&e<=1&&point<=1) return true; else return false; } };