medium 剑指 Offer 表示数值的字符串

在这里插入图片描述
在这里插入图片描述


依次判断:

数字的格式可以用A[.[B]][e|EC]或者.B[e|EC]表示,
其中A和C都是整数(可以有正负号,也可以没有),而B是一个无符号整数

c++


class Solution {
public:
    // 数字的格式可以用A[.[B]][e|EC]或者.B[e|EC]表示,
    // 其中A和C都是整数(可以有正负号,也可以没有),而B是一个无符号整数
    bool isNumber(string s) {
        if(s.size() == 0)
            return false;
        int index = 0;
        while(s[index] == ' '){  // 越过空格
            index++;  
        }
        bool numeric = scanInteger(s, index); // 越过+-号和数字;
        // 如果出现'.',
        if(s[index] == '.'){  // 越过.号
            index++;
            // .123  233.  233.666 均合法
            // 必须先判断scanUnsignedInteger, 否则 numeric true则不执行scanUnsignedInteger(s, index),那么index无法越过小数点后数字,scanUnsignedInteger函数越过数字
            numeric =  scanUnsignedInteger(s, index) || numeric ; 
            // true,false  有数字,无数字  +233.
            // true,true:  有数字,有数字  +233.666  
            // false,true: 无数字,有数字  .123 
        }     

        // 如果出现'e'或者'E',接下来跟着的是数字的指数部分
        if(s[index] == 'e' || s[index] == 'E'){
            index++;
            // 不合法: 当e或E前面没有数字时,.e1、e1
            // 不合法: 当e或E后面没有整数时,12e、12e+5.4
            numeric = numeric && scanInteger(s ,index);  // 越过+-号和数字 
        }

        while(s[index] == ' '){  // 越过结尾空格
            index++;
        }
        return numeric && index == s.size();
    }

private:  // 判断是否是+123
    // 越过+-号 
    bool scanInteger(string s, int& index){
        if(s[index]=='+' || s[index]=='-'){
            index++;
        }
        return scanUnsignedInteger(s, index);  // index指针已经指向.后一位
    }
    // 越过数字
    bool scanUnsignedInteger(string s, int& index){
        int befor = index;
        while(index != s.size() && s[index] >= '0' && s[index] <= '9'){
            index++;  
        }  // 跳出循环时 越过数字or字符串结束
        
        return index > befor;   // 有数字
    }

};


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值