zoukankan      html  css  js  c++  java
  • 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.

    思路:本题需要讨论四种情况——数字、e、'.'、正负号.

    正负号:只出现在第一个字符或e的后面一个字符;

    小数点:字符串中不能只存在小数点,也不能只含小数点和正负号,小数点不能在e后

    e:不能出现在第一个字符或最后一个字符,e前面不能没有数字。

    在处理之前,先把头尾的空格去掉,然后在进行数字、e、'.'、正负号的判断。

    class Solution {
    public:
        bool isNumber(const char *s) {
            if(strlen(s)<=0)
                return true;
            while(*s==' ')
                s++;
            const char *pEnd=s+strlen(s)-1;
            while(*pEnd==' ')
                pEnd--;
            if(*s=='+'||*s=='-')
                s++;
            const char *pBeg=s;
            int digit=0;
            int point=0;
            int e=0;
            while(*pBeg!=''&&pBeg<=pEnd)
            {
                if(isdigit(*pBeg))
                {
                    pBeg++;
                    digit++;
                }
                else if(*pBeg=='.'&&e==0)
                {
                    pBeg++;
                    point++;
                }
                else if(*pBeg=='e'&&pBeg!=s&&digit>=1)
                {
                    if(isdigit(*(pBeg+1)))
                    {
                        pBeg=pBeg+2;
                        e++;
                    }
                    else if((pBeg+2<=pEnd)&&(*(pBeg+1)=='+'||*(pBeg+1)=='-'))
                    {
                        pBeg=pBeg+2;
                        e++;
                    }
                    else
                        return false;
                }
                else
                    return false;
            }
            if(digit>=1&&e<=1&&point<=1)
                return true;
            else
                return false;
            
        }
    };
  • 相关阅读:
    ruby 实现java中的aes 加密解密
    移动端手机端web页面中背景图固定问题
    hooks 组件对应的生命周期
    React 生命周期函数总结
    Sequelize 常用增删改查函数
    如何验证SSH的连通性
    如何生成SSH密钥
    如何查看本机ssh秘钥
    如何更改本地代码仓库指向
    如何发布npm 包
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3836743.html
Copyright © 2011-2022 走看看