-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValid_Number.cpp
More file actions
104 lines (92 loc) · 2.02 KB
/
Valid_Number.cpp
File metadata and controls
104 lines (92 loc) · 2.02 KB
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
// Source : https://oj.leetcode.com/problems/valid-number/
// Author : zheng yi xiong
// Date : 2015-02-02
/**********************************************************************************
*
* 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.
* click to show spoilers.
* Update (2014-12-06):
* New test cases had been added. Thanks unfounder's contribution.
*
**********************************************************************************/
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
bool isNumber(const char *s) {
enum InputType {
SPACE,
DIGIT,
EXPONENT,
DOT,
SIGN,
NUM_INPUTS
};
const int number_state_map[][NUM_INPUTS] = {
//space,0~9, e, ., +-,
0, 1, -1, 2, 3,
5, 1, 4, 7, -1,
-1, 7, -1, -1, -1,
-1, 1, -1, 2, -1,
-1, 8, -1, -1, 6,
5, -1, -1, -1, -1,
-1, 8, -1, -1, -1,
5, 7, 4, -1, -1,
5, 8, -1, -1, -1,
};
int state = 0;
for (int i = 0; 0 != s[i]; ++i)
{
if (' ' == s[i])
{
state = number_state_map[state][SPACE];
}
else if ('0' <= s[i] && '9' >= s[i])
{
state = number_state_map[state][DIGIT];
}
else if ('e' == s[i] || 'E' == s[i])
{
state = number_state_map[state][EXPONENT];
}
else if ('.' == s[i])
{
state = number_state_map[state][DOT];
}
else if ('-' == s[i] || '+' == s[i])
{
state = number_state_map[state][SIGN];
}
else
{
return false;
}
if (-1 == state)
{
return false;
}
}
if (1 == state || 5 == state || 7 == state || 8 == state)
{
return true;
}
return false;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
string s = ". 1";
Solution so;
bool bNumber = so.isNumber(s.c_str());
return 0;
}