首页 > 代码库 > Valid Number
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 #include <string.h> 2 #include <iostream> 3 #include <ctype.h> 4 5 #include <fstream> 6 7 using namespace std; 8 9 class Solution10 {11 public:12 bool isNumber(const char *s)13 {14 bool has_front_num = false, has_back_num = false, has_e = false;15 int len = strlen(s);16 int i = 0;17 18 while(i < len && ‘ ‘ == s[i])19 i++;20 21 if(i == len) return false;22 23 if(i < len && (s[i] == ‘+‘ || s[i] == ‘-‘))24 i++;25 26 while(i < len && isdigit(s[i]))27 {28 i++;29 has_front_num = true;30 }31 32 if(i < len && s[i] == ‘.‘)33 i++;34 35 while(i < len && isdigit(s[i]))36 {37 i++;38 has_front_num = true;39 }40 41 if(i < len && (s[i] == ‘e‘ || s[i] == ‘E‘) && has_front_num)42 {43 i++;44 has_e = true;45 if(i == len) return false;46 }47 48 49 if(i < len && (s[i] == ‘+‘ || s[i] == ‘-‘) && has_e)50 i++;51 52 while(i < len && isdigit(s[i]) && has_e)53 {54 i++;55 has_back_num = true;56 }57 58 while(i < len && s[i] == ‘ ‘)59 i++;60 61 if(i == len && has_e && has_back_num)62 return true;63 else if(i == len && !has_back_num && !has_e && has_front_num)64 return true;65 66 return false;67 }68 };69 70 int main()71 {72 ifstream cin("aa");73 Solution s;74 char *ss;75 while(cin >> ss)76 cout << s.isNumber(ss) << endl;77 return 0;78 }
Valid Number
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。