【LeetCode】65. Valid Number

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.

 

这题定义很模糊,据说这就是考察应聘者思考与沟通能力的。

其实就是针对用例编程。。

class Solution {
public:
    bool isNumber(string s) {
        int i = 0;
        //skip prefix spaces
        while(i < s.size() && s[i] == ' ')
            i ++;
        if(i == s.size())
        //all space
            return false;
        
        //check sign
        if(s[i] == '+' || s[i] == '-')
            i ++;
        //begin 
        int dignum = 0;
        int dotnum = 0;
        while(s[i] == '.' || (s[i] >= '0' && s[i] <= '9'))
        {
            if(s[i] == '.')
                dotnum ++;
            else 
                dignum ++;
            i ++;
        }
        if(dotnum > 1)
            return false;
        if(dignum < 1)
            return false;
        
        if(s[i] == 'e')
        {
            i ++;
            dignum = 0;
            //check sign
            if(s[i] == '+' || s[i] == '-')
                i ++;
            while(s[i] >= '0' && s[i] <= '9')
            {
                dignum ++;
                i ++;
            }
            if(dignum < 1)
                return false;
        }
        
        //check suffix
        while(i < s.size() && s[i] == ' ')
            i ++;
        if(i == s.size())
            return true;
        else
            return false;
    }
};

posted @ 2014-12-10 10:59  陆草纯  阅读(201)  评论(0编辑  收藏  举报