[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.

要写对这题着实不容易,很多细节需要考虑。先看看测试用例有哪些,然后再写就比较有针对性。最后看看哪些test case错了,再修一下bug。

 1 class Solution {
 2 public:
 3     bool isNumber(const char *s) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if (s == NULL)
 7             return false;
 8             
 9         while(isspace(*s))
10             s++;
11             
12         if (*s == '+' || *s == '-')
13             s++;
14             
15         bool eAppear = false;
16         bool dotAppear = false;
17         bool firstPart = false;
18         bool secondPart = false;
19         bool spaceAppear = false;
20         while(*s != '\0')
21         {
22             if (*s == '.')
23             {
24                 if (dotAppear || eAppear || spaceAppear)
25                     return false;
26                 else
27                     dotAppear = true;
28             }
29             else if (*s == 'e' || *s == 'E')
30             {
31                 if (eAppear || !firstPart || spaceAppear)
32                     return false;
33                 else
34                     eAppear = true;
35             }
36             else if (isdigit(*s))
37             {
38                 if (spaceAppear)
39                     return false;
40                     
41                 if (!eAppear)
42                     firstPart = true;
43                 else
44                     secondPart = true;
45             }
46             else if (*s == '+' || *s == '-')
47             {
48                 if (sapceAppear)
49                     return false;
50                     
51                 if (!eAppear || !(*(s-1) == 'e' || *(s-1) == 'E'))
52                     return false;
53             }
54             else if (isspace(*s))
55                 spaceAppear = true;
56             else
57                 return false;
58                 
59             s++;            
60         }
61         
62         if (!firstPart)
63             return false;
64         else if (eAppear && !secondPart)
65             return false;
66         else
67             return true;
68     }
69 };

转载于:https://www.cnblogs.com/chkkch/archive/2012/11/18/2775938.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值