[LeetCode] Valid Number

解决LeetCodeOJ中复杂数字验证问题的系统方法

I guess some of you may have noticed that this seemingly simple problem has the lowest acceptance rate among all problems on the LeetCode OJ. Well, some of you may also complain about the annoying large number of special cases and have no idea of how to handle them systematically. Well, this link provides a nicely systematic idea, which gives a very clean and clear code. Take a look at it and you will become happy with this problem :-)

The code is rewritten as follows.

 1 class Solution {
 2 public:
 3     bool isNumber(string s) {
 4         int i = 0, n = s.length();
 5         // Skip the leading spaces
 6         while (i < n && isspace(s[i])) i++;
 7         // Skip the sign
 8         if (s[i] == '+' || s[i] == '-') i++;
 9         // Check for the following significant parts
10         int digits = 0, dots = 0;
11         while (i < n && (isdigit(s[i]) || s[i] == '.')) {
12             if (isdigit(s[i])) digits++;
13             else dots++;
14             i++;
15         }
16         if (digits < 1 || dots > 1) return false;
17         if (i == n) return true;
18         // Check for the exponential parts
19         if (s[i] == 'e') {
20             i++;
21             if (i == n) return false;
22             if (s[i] == '+' || s[i] == '-') i++;
23             digits = 0;
24             while (i < n && (isdigit(s[i]))) {
25                 digits++;
26                 i++;
27             }
28             if (digits < 1) return false;
29         }
30         // Skip the trailing spaces
31         while (i < n && isspace(s[i])) i++;
32         return i == n;
33     }
34 };

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值