-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathvalidNumber.c
129 lines (129 loc) · 2.42 KB
/
validNumber.c
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define true 1
#define false 0
typedef int bool;
char *strip(char *src, char *dest)
{
if (src == NULL)
return NULL;
if (strlen(src) == 0) {
dest[0] = 0;
return 0;
}
int i = 0, j = strlen(src) - 1;
while (isblank(src[i])) i++;
while (isblank(src[j])) j--;
int k = 0;
while (i <= j) {
dest[k++] = src[i++];
}
dest[k] = 0;
return dest;
}
bool isInteger(char *s)
{
if (s == NULL || strlen(s) == 0)
return false;
int i = 0;
int len = strlen(s);
if (s[i] == '+' || s[i] == '-') {
// + -
if (len == 1)
return false;
i++;
}
for (; i < len; ++i) {
if (!isdigit(s[i])) {
return false;
}
}
return true;
}
bool isE(char c)
{
if (c == 'e' || c == 'E')
return true;
return false;
}
bool isSci(char *s)
{
if (s == NULL || strlen(s) == 0)
return false;
int len = strlen(s);
if (len == 1) {
return isdigit(s[0]);
}
for (int i = 0; i < len; ++i) {
if (isE(s[i])) {
return isInteger(s + i + 1);
}
if (!isdigit(s[i]))
return false;
}
return true;
}
bool isNumber(char *s)
{
if (s == NULL)
return false;
char *striped = malloc(sizeof(char) * strlen(s));
strip(s, striped);
int len = strlen(striped);
if (len == 0)
return false;
int i = 0;
if (striped[i] == '+' || striped[i] == '-') {
// 只有+ - 号非法
if (len == 1)
return false;
++i;
}
for(; i < len; ++i) {
if (isE(striped[i])) {
// 出现e,但还没有出现小数点, e前面必须是整数,e后面也是整数
if (i >= 1 && isdigit(striped[i - 1])) {
// 1e123
return isInteger(striped + i + 1);
} else {
// e2 -e2 Invalid
return false;
}
}
// 出现小数点
if (striped[i] == '.') {
// 小数点前面是整数,后面没有内容也是合法的,比如(5.), (0.)都是合法的小数
if (i >= 1 && isdigit(striped[i - 1]) && i == len - 1) {
// -4. Valid
return true;
}
// (.e1) (.e)是非法的
if (i == 0 && isE(striped[i + 1])) {
// .e1 Invalid
return false;
}
// 小数点后面是科学计数法是正确的。
return isSci(striped + i + 1);
}
if (!isdigit(striped[i])) {
return false;
}
}
return true;
}
int main(int argc, char **argv)
{
char s[20];
while(fgets(s, 20, stdin) != NULL) {
int len = strlen(s);
s[len - 1] = 0;
if (isNumber(s))
printf("%s => true\n", s);
else
printf("%s => false\n", s);
memset(s, 0, sizeof(s));
}
return 0;
}