Valid Number leetcode

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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

这道题之所以是hard难度,是因为它隐含的输入种类非常之多,要想将所有的情况考虑完全,并且找出这些情况之间的逻辑关系,用尽可能少的代码实现出来,而不冗余,难度非常之大。

还好题目中给出了5种可能的输入情况,减少了我们试错的次数。

总结一下情况:

1.可以有+-号(如果有e,前后的数需要分别判断,这里没有"+-"和"-+"的坑爹情况)

2.可以有小数点(但只能有一个)

3.不能有字母(e除外)

4.必须有数字(如果有e,e的前面数和后面的数需要分别判断)

5.可以有空格,但必须出现在字符串的前面和后面(像这种 "-   1"、"1   e   1"都是不被允许的)

这些情况都是无数的先辈被折磨到口吐鲜血才总结出来的。

我是个懒人,也不是自虐狂,所以就直接拿来主义了。

不过程序是自己实现了

bool isNumber(string s) {
    int i = 0;
    while (s[i] == ' ')
        i++;
    if (s[i] == '+' || s[i] == '-')
        i++;
    int n_point = 0, n_num = 0;
    while (isdigit(s[i]) || s[i] == '.')
        s[i++] == '.' ? n_point++ : n_num++;
    if (n_point > 1 || n_num < 1)
        return false;

    if (s[i] == 'e') {
        i++;
        if (s[i] == '+' || s[i] == '-')
            i++;
        int n_num = 0;
        while (isdigit(s[i]))
        {
            i++;
            n_num++;
        }
        if (n_num < 1)
            return false;
    }
    while (s[i] == ' ')
        i++;
    return i == s.length();
}

总结:

想好了再编程,清楚了需求再编程,别手犯贱!

原文地址:https://www.cnblogs.com/sdlwlxf/p/5116254.html