题解 | #表示数值的字符串#
表示数值的字符串
https://www.nowcoder.com/practice/e69148f8528c4039ad89bb2546fd4ff8
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param str string字符串
* @return bool布尔型
*/
bool isNumeric(string str) {
// 当数组是空的 直接返回null
if(str.length()==0)
return false;
//false:连续的+-号
int index=0;
if(str[index]=='+' ||str[index] =='-')
{
index++;
if(str[index]=='+' ||str[index] =='-')
return false;
}
//false:出现完正负号就‘/0’
if(str[index] == '\0')
return false;
//定义小数点、e、num
int dot=0,e=0,num=0;
while(str[index] != '\0'){
//要考虑是否有空格 先删掉空格
while(str[index] == ' ')
{
index++;
if(str[index]=='\0'){
if(dot==0 && num==0 && e==0)
return false;
return true;
}
}
// 对数字时进行讨论 num++
if(str[index] >= '0' && str[index]<='9'){
num++;
index++;
}
//对小数点时进行讨论 如果前面已经有小数点或者e了直接false(连续小数点)
else if(str[index] =='.'){
if(dot>0 || e>0 )
return false;
dot++;
index++;
//考虑结束完.后 排除仅有. 的情况
if(str[index] == '\0'&&num==0)
return false;
}
//对e时进行讨论 e前面没有数组 出现两个e 直接false
else if(str[index] =='e'|| str[index] =='E'){
if(num==0 || e>0)
return false;
e++;
index++;
//判断是否有重复正负号错误
if(str[index]=='+' ||str[index] =='-')
{
index++;
if(str[index]=='+' ||str[index] =='-')
return false;
}
// e后面没有数字
if(str[index] == '\0')
return false;
}
else{
return false;
}
}
return true;
}
};

查看24道真题和解析