首页 > 代码库 > Valid Number
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 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。