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

Valid Number

时间:2015-01-24 11:30:31      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

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 Solution
10 {
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

标签:

原文地址:http://www.cnblogs.com/lxd2502/p/4245538.html

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