当前位置:编程学习 > C/C++ >>

Valid Number

题目:


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.

分析:此题的确很难,难点在于需要考虑的情况太多,列举如下:

1、空格不能出现在数字之间

2、点和e最多只能出现一次

3、出现e之前必须有数字

4、正负号要么出现在数字的最前面,要么出现在紧接着e后面

5、e后面必须还得有数字

6、正负号最多出现两次


代码如下:

//注意:刚出现的空格不用计数,直到数字、点、e或者正负号出现后的空格才需要计数。


        bool isNumber(const char *s) {
        if(s==NULL)return false;
        int num=0,numdot=0,nume=0,numkg=0,numsign=0;//分别表示数字、点、e、空格以及正负号的个数
        bool flag=false;
        while(*s!='\0')
        {
            if(int(*s-'0')>=0&&int(*s-'0')<=9)
            {
                if(numkg>0)
                {
                    return false;
                }
                flag=false;
                num++;
                s++;
            }
            else
            {
                if(*s=='.')
                {
                    if(numdot>0||numkg>0||nume>0)
                    {
                        return false;
                    }
                    numdot++;
                    s++;
                }
                else
                {
                    if(*s==' ')
                    {
                        if(num!=0||numdot!=0||nume!=0||numsign!=0)
                        {
                            numkg++;
                        }
                        s++;
                    }
                    else
                    {
                        if(*s=='e')
                        {
                            if(num<=0||nume>0||numkg>0)
                            {
                                return false;
                            }
                            s++;
                            nume++;
                            flag=true;
                        }
                        else
                        {
                            if(*s=='+'||*s=='-')
                            {
                                if((nume==0&&num>0)||(nume==0&&numsign>0)||(nume==0&&numdot>0))
  &n

补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,