【Leetcode】【Hard】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.

 

本题需要考虑:

1、字符前的空格

2、字符正负号

3、检查是否是数字,数字中可以包含一个‘.’小数点,数字至少应存在一位

4、略过数字和点后,检查是否有‘e’,如果有:

  (1)检查指数是否有正负

  (2)检查其后是否有数字,数字至少存在一位

5、字符后的空格

6、最后遇到'\0'则返回true,否则false

 

代码:

 1 class Solution {
 2 public:
 3     bool isNumber(string s) {
 4         int i = 0;
 5     
 6         // skip the whilespaces
 7         for(; s[i] == ' '; i++) {}
 8     
 9         // check the significand
10         if(s[i] == '+' || s[i] == '-') i++; // skip the sign if exist
11     
12         int n_nm, n_pt;
13         for(n_nm=0, n_pt=0; (s[i]<='9' && s[i]>='0') || s[i]=='.'; i++)
14             s[i] == '.' ? n_pt++:n_nm++;       
15         if(n_pt>1 || n_nm<1) // no more than one point, at least one digit
16             return false;
17     
18         // check the exponent if exist
19         if(s[i] == 'e') {
20             i++;
21             if(s[i] == '+' || s[i] == '-') i++; // skip the sign
22     
23             int n_nm = 0;
24             for(; s[i]>='0' && s[i]<='9'; i++, n_nm++) {}
25             if(n_nm<1)
26                 return false;
27         }
28     
29         // skip the trailing whitespaces
30         for(; s[i] == ' '; i++) {}
31     
32         return s[i]==0;  // must reach the ending 0 of the string
33     }
34 };

 

posted @ 2015-08-31 22:39  胡潇  阅读(577)  评论(0编辑  收藏  举报