[LeetCode 65] 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.

---------------------------------------------------------------------------------------------------------------------------------

 此题判断一个字符串是否是有效的数字表达式,主要难点在如果考虑到科学计数法会出现各种corner case:

如 - 4.5e2, 5.3e, 4e4.6, +e9, e5, 4.9 e1等等都是错误的。

各种if条件判断很扰人,但其实如果把这个数字分为e之前和之后两部分来分别考虑会简化不少,也容易实现,直接将难度从Hard降为Medium.

把各种情况概况起来就是:

1)出现在e之前的应该为一个有效的浮点数,e之后的应该为有效整数。

2)有效浮点数规则:a)正负号只能出现在最前面;b)小数点只有一个; c)中间不能出现其他非数字字符; d)至少有一个数字

3)有效整数规则:    a)正负号只能出现在最前面;b)没有小数点;        c)中间不能出现其他非数字字符; d)至少有一个数字

class Solution {
public:
    bool isNumber(string s) {
        s.erase(0, s.find_first_not_of(" "));
        s.erase(s.find_last_not_of(" ")+1);
        int pos = s.find_first_of("e");
        if(pos == -1) return isValidfloat(s);
        else return isValidfloat(s.substr(0, pos)) && isValidInteger(s.substr(pos+1));
    }
    bool isValidfloat(string s){
        if(!s.empty() && (s[0] == '-' || s[0] == '+')) s.erase(s.begin());
        int n_dot = 0;
        for(int i=0; i<s.size(); i++){
            if(s[i] == '.') n_dot++;
            else if(!isdigit(s[i])) return false;
        }
        return n_dot <= 1 && s.size() > n_dot;
    }
    bool isValidInteger(string s){
        if(!s.empty() && (s[0] == '-' || s[0] == '+')) s.erase(s.begin());
        for(int i=0; i<s.size(); i++){
            if(!isdigit(s[i])) return false;
        }
        return s.size();
    }
    
};
View Code

 

转载于:https://www.cnblogs.com/naturesound/p/7848458.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值