题目:
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;
}
}
};
本文深入探讨如何通过编程逻辑判断给定字符串是否为有效的数值形式,包括整数、小数及科学计数法,并通过实例代码展示实现过程。
1017

被折叠的 条评论
为什么被折叠?



