【Leetcode】【Hard】Valid Number

Validate if a given string is numeric.git

Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => trueui

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.spa

 

本題須要考慮:code

一、字符前的空格blog

二、字符正負號ip

三、檢查是不是數字,數字中能夠包含一個‘.’小數點,數字至少應存在一位rem

四、略過數字和點後,檢查是否有‘e’,若是有:string

  (1)檢查指數是否有正負it

  (2)檢查其後是否有數字,數字至少存在一位io

五、字符後的空格

六、最後遇到'\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 };
相關文章
相關標籤/搜索