leetcode-Valid Number

22 篇文章 0 订阅
15 篇文章 0 订阅

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.

题意:判断是一个字符串是不是合法的数字,数字可以是小数

分析:这道题隐含了很多条件,我也是WA了无数次才试出来的。。包括:

(1)忽略前导空格和后缀空格,中间部分必须是合法数字

(2)数字可以以‘+’,‘-’开头

(3)小数点只能出现一次,但是小数点之前或之后可以没有数字(一边有数字即可)

(4)e只能出现一次,左右必须都有数字,e左侧可以是小数(也就是说左边相邻字符可能是小数点),右侧必须是整数(但是可以以‘+’,‘-’开头)

代码:

class Solution {
public:
    bool isNum(char c)
    {
        if(c>='0' && c<='9') return true;
        return false;
    }
    bool isNumber(const char *s) {
        int len = strlen(s);
        if(len==0) return false;
        int pos = 0;
        while(s[pos]==' ') pos++;
        if(pos>=len) return false;
        
        int st=pos;
        if(s[st]=='-' || s[st]=='+') st++;
        
        bool isdot=false,ise=false;
        
        for(pos=st; pos<len && s[pos]!=' '; pos++)
        {
            if(isNum(s[pos]))
                continue;
            else if(s[pos]=='.')
            {
                if(isdot) return false;
                isdot = true;
                int now=0;
                if(pos>st && isNum(s[pos-1])) now++;
                if(pos<len-1 && isNum(s[pos+1])) now++;
                if(now<1) return false;
            }
            else if(s[pos]=='e')
            {
                if(ise) return false;
                ise = true;
                isdot = true;
                int now=0;
                if(pos>st && (isNum(s[pos-1]) || s[pos-1]=='.')) now++;
                if(pos<len-1) 
                {
                    if(s[pos+1]=='+'||s[pos+1]=='-')
                    {
                        pos++;
                        if(pos<len-1 && isNum(s[pos+1])) now++;
                    }
                    else if(isNum(s[pos+1]))
                        now++;
                }
                if(now<2) return false;
            }
            else 
                return false;
        }
        for(; pos<len; pos++)
            if(s[pos]!=' ') return false;
        return true;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值