2016/08/10

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

解法真是非常呆,不過直覺也不是壞事
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
bool isNumber(char* s) {
    int len=strlen(s);
    int i;
    bool havedot=false;
    bool havee=false;
    bool havespace=false;
    bool havenum=false;
    bool havesymbol=false;

    for(i=0; i<len; i++)
    {
        if(s[i]<0x30 || s[i]>0x39)
        {
            if(' ' == s[i])
            {
                if(havenum || havee || havedot || havesymbol)
                {
                    havespace = true;
                }
            }
            else if('.' == s[i])
            {
                if(havee || havedot || havespace)
                {
                    return false;
                }
                else
                {
                    havedot = true;
                }
            }
            else if('e' == s[i])
            {
                if(havee || !havenum)
                {
                    return false;
                }
                else
                {
                    havee = true;
                    havenum = false;
                    havesymbol = false;
                }
            }
            else if('+' == s[i] || '-' == s[i])
            {
                if (havee)
                {
                    if (havesymbol || havenum)
                    {
                        return false;
                    }
                }
                else
                {
                    if (havesymbol || havenum || havedot)
                    {
                        return false;
                    }
                }
                havesymbol = true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            if(havespace)
            {
                return false;
            }
            havenum = true;
        }
    }
    return havenum;
}

沒有留言: