码迷,mamicode.com
首页 > 其他好文 > 详细

Valid Number

时间:2014-08-25 16:52:14      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   strong   for   ar   div   log   

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 class Solution {
 2 public:
 3     bool isNumber( const char *s ) {
 4         return ParseDecimal( s ) && ParseScientific( s ) && *s == \0;
 5     }
 6 private:
 7     bool ParseDigits( const char* &s ) {
 8         if( *s < 0 || *s > 9 ) { return false; }
 9         while( *s >= 0 && *s <= 9 ) { ++s; }
10         return true;
11     }
12     bool ParseDecimal( const char* &s ) {
13         while( *s ==   ) { ++s; }
14         if( *s == + || *s == - ) {
15             if( *(++s) == \0 ) { return false; }
16         }
17         bool flag1 = ParseDigits( s );
18         if( *s == . ) { ++s; }
19         bool flag2 = ParseDigits( s );
20         return flag1 || flag2;
21     }
22     bool ParseScientific( const char* &s ) {
23         if( *s == e ) {
24             ++s;
25             if( *s == + || *s == - ) {
26                 if( *(++s) == \0 ) { return false; }
27             }
28             if( !ParseDigits( s ) ) { return false; };
29         }
30         while( *s ==   ) { ++s; }
31         return true;
32     }
33 };

 

Valid Number

标签:style   blog   color   io   strong   for   ar   div   log   

原文地址:http://www.cnblogs.com/moderate-fish/p/3934704.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!