Leetcode-65.Valid Number

Problem Description:
Validate if a given string is numeric.

Some examples:
“0” => true
” 0.1 ” => true
“abc” => false
“1 a” => false
“2e10” => true


Analysis:
This link provides a nicely systematic idea.
1. skip the leading blank space
2. check the leading sign and check the number of digits. if there is a dot, A valid num has no more than 1 point and at least one digit
3. check if the exponent part is valid. We do this if the significand is followed by ‘e’. Simply skip the leading sign and count the number of digits and can’t have a dot. A valid exponent contain at least one digit.
4. skip the trailing white space
Some test case:
’ .’ ; ’ e’ ; ‘000242e+6’; ‘0e’; ‘e9’; ‘12e1.2’,’+.8 ‘; ’ ‘;
The code is as follows:

bool isNumber(string s)
{
    int i = 0;
    //skip the whitespaces
    for (; s[i] == ' '; ++i){}
    // check the significand
    // skip the sign if exist
    if (s[i] == '+' || s[i] == '-') ++i;

    int n_nm, n_pt;
    for (n_nm = 0, n_pt = 0; isdigit(s[i]) || s[i] == '.'; ++i)
        s[i] == '.'? n_pt++ : n_nm ++;
    if (n_pt > 1 || n_nm < 1) return false;

    //check the exponent if exist
    if (s[i] == 'e')
    {
        ++i;
        if (s[i] == '+' || s[i] == '-') ++i;
        int n_nm = 0;
        for (; isdigit(s[i]); ++i, n_nm++){}
        if (n_nm < 1) return false;
    }

    for (; s[i] == ' '; i++){}
    return s[i] == 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值