LeetCode-Valid Number

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.

Solution:

Code:

<span style="font-size:14px;">class Solution {
public:
    bool isDigit(const char &c) {
        int temp = c - '0';
        if ((0 <= temp) && (temp <= 9))
            return true;
        return false;
    }
    
    bool isWithoutSign (const char *s, int &index) {
        int countE = 0;
        int countP = 0;
        bool containBlank = false;
        bool containDigit = false;
        bool containSign = false;
        bool beforeE = false;
        bool afterE = false;
        bool beforeP = false;
        bool afterP = false;
        for (int i = index; i < strlen(s); i++) {
            if (s[i] == 'e') {
                if (containBlank) return false;
                countE++;
                if (countE > 1) return false;
            } else if (s[i] == '.') {
                if (containBlank) return false;
                if (countE) return false;
                countP++;
                if (countP > 1) return false;
            } else if (isDigit(s[i])) {
                if (containBlank) return false;
                containDigit = true;
                if (!countP) beforeP = true;
                else afterP = true;
                if (!countE) beforeE = true;
                else afterE = true;
            } else if ((s[i] == '+') || (s[i] == '-')) {
                if (containBlank) return false;
                if (containSign) return false;
                if (s[i-1] != 'e') return false;
                containSign = true;
            } else if (s[i] == ' ') {
                containBlank = true;
            } else {
                return false;
            }
        }
        if ((countE) && (!(beforeE && afterE))) return false;
        if ((countP) && (!(beforeP || afterP))) return false;
        if (!containDigit) return false;
        return true;
    }
    
    bool isNumber(const char *s) {
        bool result = false;
        int index = 0;
        while ((s[index] == ' ')) {
            index++;
        }
        if ((s[index] == '+') || (s[index] == '-')) {
            index++;
            result = isWithoutSign(s, index);
        } else {
            result = isWithoutSign(s, index);
        }
        return result;
    }
};</span>



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值