剑指 Offer 20. 表示数值的字符串

方法:分为几个部分判断 DA[.B][E/eC] D

其中D表示前后的空格,需要处理,跳过即可

A可以带正负号 有符号数
B无符号数
C可以为有符号数(带+-号)

小数点.后面必须是无符号数或者没有 如1.
 同时小数点.前面可以没有数字 所以用numeric = findUnsignedInt(s,pos) || numeric(或)

E/e前后必须有数字 因此用 numeric = numeric && findInt(s,pos)

class Solution {
public:
    bool isNumber(string s) {
        //DA[.B][E/eC] D

        //A可以带正负号 有符号数
        //B无符号数
        //C有符号数

        //处理前面的空格
        int pos = 0;
        while(s[pos]!='\0' && s[pos]==' ')
        {
            ++pos;
        }
        //A部分
        
        bool numeric = findInt(s,pos);
        //B部分
        if(s[pos]=='.')
        {
            //.后面必须是无符号数或者没有 如1.
            //.前面可以没有数字 所以用||
            ++pos; //看小数点后的呀
            numeric = findUnsignedInt(s,pos) || numeric;
        }
        //C部分
        if(s[pos]=='e'||s[pos]=='E')
        {
            ++pos; //看e后面的!!
            numeric = numeric && findInt(s,pos);
        }
        while(s[pos]!='\0' && s[pos]==' ')
        {
            ++pos;
        }
        return numeric && (s[pos]=='\0');
    }
    
    bool findUnsignedInt(const string& s,int& pos)
    {
        int save = pos;
        while(s[pos]!='\0' && s[pos]>='0' && s[pos]<='9')
        {
            ++pos;
        }
        return pos>save; //说明有数字
    }
    bool findInt(const string& s,int& pos)
    {
        //
        if( s[pos]=='-' || s[pos]=='+')
        {
            ++pos;
        }
        return findUnsignedInt(s,pos);

    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值