表示数值的字符串

来源:互联网 发布:华为 云计算部门 编辑:程序博客网 时间:2024/06/04 22:46

题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串”+100”,”5e2”,”-123”,”3.1416”和”-1E-16”都表示数值。 但是”12e”,”1a3.14”,”1.2.3”,”+-5”和”12e+4.3”都不是。

从前到后判断即可

需要注意-.123这样的数字也是对的。。。。测试集太小,代码仅供参考。。。

class Solution {public:    bool isNumeric(char* string)    {        char* str=string;        if(str==NULL)            return false;                if(*str=='+'||*str=='-')            ++str;        if(*str=='\0')            return false;        if((*str<'0'||*str>'9')&&*str!='.'){            return false;        }        if(*str!='.')        while(*str!='\0'&&(*str>='0'&&*str<='9'))            ++str;        if(*str=='\0')            return true;        else if(*str=='.')            {            ++str;            if(*str=='\0'||(*str<'0'||*str>'9'))                return false;            ++str;            while(*str!='\0'&&(*str>='0'&&*str<='9'))                ++str;            if(*str=='\0')            return true;            if(*str=='e'||*str=='E')                return judge_e(str);             else                return false;                   }        else if(*str=='e'||*str=='E')            {            return judge_e(str);         }        else            return false;    }bool judge_e(char *str)    {    ++str;    if(*str=='+'||*str=='-')        ++str;    if(*str=='\0')        return false;    while(*str!='\0'&&(*str>='0'&&*str<='9'))         ++str;    if(*str=='\0')    return true;    else     return false;}};
0 0
原创粉丝点击