題目:
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.
解題思路:這是一道很無聊的題,只要明確了規則就可以通過。leetcode上這道題的通過率只有10+%,我認為是由於規則不清晰引起的。我也是在不斷的錯誤中明確了“有效”的具體規則定義以後才通過的。
代碼:
class Solution { public: bool isNumber(const char *s) { bool num_begin=false,e_begin=false,dot=false,last_space=false,dot_exist=false,e_exist=false,dot_before=false,dot_after=false,zf_begin=false; if(s==nullptr)return false; while(*s!='\0'){ if(isalpha(*s)){ if(!num_begin||*s!='e'){ return false; } if(*s=='e'){ if(e_begin||zf_begin||e_exist){ return false; }else{ if(dot&&!dot_before)return false; e_begin=true; e_exist=true; dot=false; s++; continue; } } } if(isspace(*s)){ if(!num_begin){ s++; continue; }else{ last_space=true; s++; continue; } } if(isdigit(*s)){ if(!dot_exist){ dot_before=true; }else{ dot_after=true; } num_begin=true; if(last_space)return false; if(dot){ dot=false; s++; continue; } if(e_begin){ e_begin=false; s++; continue; } if(zf_begin){ zf_begin=false; s++; continue; } s++; continue; } if(!isalnum(*s)&&!isspace(*s)){ if(!dot&&*s=='.'&&!e_begin&&!dot_exist&&!e_exist){ if(last_space)return false; dot=true; dot_exist=true; num_begin=true; zf_begin=false; s++; continue; }else if(e_begin&&(*s=='-'||*s=='+')){ e_begin=false; zf_begin=true; s++; continue; }else if(!num_begin&&(*s=='-'||*s=='+')){ num_begin=true; zf_begin=true; s++; continue; }else{ return false; } } s++; } if(num_begin&&!e_begin&&(dot_before||dot_after)&&!zf_begin){ return true; }else{ return false; } } };