[Leetcode] Valid Number

本文介绍了一个C++实现的字符串到数字的解析方法,通过三个核心函数isNumber、isDecimal和isInteger完成对输入字符串的有效判断。代码首先去除字符串两端空白字符,并检查字符串是否为空,然后针对'e'或'E'进行特殊处理,分别判断小数部分和整数部分的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class Solution {
public:
    bool isNumber(const char *s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (s == NULL) return false;
        if (strlen(s) == 0) return false;
        
        int begin = 0;
        int end = strlen(s) - 1;
        while (s[begin] == ' ') ++begin;
        while (s[end] == ' ') --end;

        if (begin > end) return false;
        
        int idx = begin;
        while (idx <= end)
        {
            if (s[idx] == 'e' || s[idx] == 'E')
                return isDecimal(s, begin, idx - 1) && isInteger(s, idx + 1, end);
            ++idx;
        }
        
        return isDecimal(s, begin, end);
    }
    
    bool isDecimal(const char* s, int begin, int end)
    {
        if (begin <= end)
        {
            int idx = begin;
            bool hasDot = false;
            bool hasDigit = false;
            if (s[idx] == '+' || s[idx] == '-')
                ++idx;
            while (idx <= end)
            {
                if (s[idx] >= '0' && s[idx] <= '9')
                {
                    ++idx;
                    hasDigit = true;
                    continue;
                }
                else if (s[idx] == '.')
                {
                    if (!hasDot)
                    {
                        ++idx;
                        hasDot = true;
                        continue;
                    }
                    else
                        return false;
                }
                else
                    return false;
                
            }
            return hasDigit;
        }
        return false;
    }
    
    bool isInteger(const char* s, int begin, int end)
    {
        if (begin <= end)
        {
            int idx = begin;
            bool hasDigit = false;
            if (s[idx] == '+' || s[idx] == '-')
                ++idx;
            while (idx <= end)
            {                
                if (s[idx] >= '0' && s[idx] <= '9')
                {
                    ++idx;
                    hasDigit = true;
                }
                else
                    return false;
   
            }
            return hasDigit;
        }
        
        return false;
    }
};


注: 参照qingli代码写出 (http://blog.youkuaiyun.com/maqingli87/article/details/8010737)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值