-
Notifications
You must be signed in to change notification settings - Fork 1
/
54_表示数值的字符串
112 lines (99 loc) · 1.87 KB
/
54_表示数值的字符串
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <iostream>
using namespace std;
/*
题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。
例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。
但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
*/
class Solution
{
public:
bool isNumeric(char* string)
{
if (string == NULL)
{
return false;
}
bool IsSymbol = false;
bool IsE = false;
bool IsPoint = false;
char *p = string;
// 处理符号位
if (*p < '0' || *p > '9')
{
if (*p == '+' || *p == '-')
{
++p;
}
else
{
return false;
}
}
while (*p != '\0')
{
if (*p == 'e' || *p == 'E')
{
if (*(p + 1) == '\0')
{
return false;
}
else if (*(p + 1) == '-' || *(p + 1) == '+' )
{
p += 2;
IsPoint = true;
}
else if (*(p + 1) <= '9' && *(p + 1) >= '0')
{
++p;
}
else
{
return false;
}
}
if (*p == '.' )
{
if (IsPoint == false)
{
IsPoint = true;;
++p;
}
else
{
return false;
}
continue;
}
if (*p < '0' || *p > '9')
{
return false;
}
++p;
}
return true;
}
};
void Test()
{
cout << Solution().isNumeric("12345") << endl;
cout << Solution().isNumeric("+100") << endl;
cout << Solution().isNumeric("-111") << endl;
cout << Solution().isNumeric("10.125") << endl;
cout << Solution().isNumeric("0.345") << endl;
cout << Solution().isNumeric("5e2") << endl;
cout << Solution().isNumeric("-1E-16") << endl;
cout << Solution().isNumeric("123.45e+6") << endl;
cout << Solution().isNumeric("600.") << endl;
cout << "_____" << endl;
cout << Solution().isNumeric("12e") << endl;
cout << Solution().isNumeric("1a3.14") << endl;
cout << Solution().isNumeric("+-5") << endl;
cout << Solution().isNumeric("12e+4.3") << endl;
}
int main()
{
Test();
return 0;
}