8000 add valid number solution · leetcoders/LeetCode@c937481 · GitHub
[go: up one dir, main page]

Skip to content

Commit c937481

Browse files
author
applewjg
committed
add valid number solution
Change-Id: I40645c9d5c0874cd3402c3e92fbfc76b1f68b854
1 parent 31841cd commit c937481

File tree

1 file changed

+26
-4
lines changed

1 file changed

+26
-4
lines changed

ValidNumber.h

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
/*
2-
Author: Annie Kim, anniekim.pku@gmail.com
2+
Author: Annie Kim, anniekim.pku@gmail.com : Andy, nkuwjg@gmail.com
33
Date: May 25, 2013
4-
Update: Sep 30, 2013
4+
Update: Feb 7, 2015
55
Problem: Valid Number
66
Difficulty: Hard
7-
Source: http://leetcode.com/onlinejudge#question_65
7+
Source: https://oj.leetcode.com/problems/valid-number/
88
Notes:
99
Validate if a given string is numeric.
1010
Some examples:
@@ -21,7 +21,7 @@
2121

2222
class Solution {
2323
public:
24-
bool isNumber(const char *s) {
24+
bool isNumber_1(const char *s) {
2525
enum InputType {INVALID, SPACE, SIGN, DIGIT, DOT, EXPONENT};
2626
int transitionTable[][SPACEEND] =
2727
{ /* 0 1 2 3 4 5 */
@@ -57,4 +57,26 @@ class Solution {
5757
bool validFinal[] = {0, 0, 0, 1, 0, 0, 1, 1, 1};
5858
return validFinal[last];
5959
}
60+
bool isNumber_2(const char *s) {
61+
bool dot = false, digit = false, exp = false;
62+
while (*s == ' ') ++s;
63+
if (*s == '-' || *s == '+') ++s;
64+
if (*s == 0) return false;
65+
for (;*s != '\0' && *s != ' '; ++s) {
66+
if (isdigit(*s)) digit = true;
67+
else if (*s == 'e' || *s == 'E') {
68+
if (exp == true || digit == false || *(s+1) ==' ' || *(s+1) =='\0') return false;
69+
exp = true;
70+
} else if (*s == '.') {
71+
if (dot == true || exp == true) return false;
72+
if (digit == false && (*(s+1) ==' ' || *(s+1) =='\0')) return false;
73+
dot = true;
74+
} else if (*s == '-' || *s == '+') {
75+
if (*(s+1) == ' ' || *(s+1) == '\0') return false;
76+
if (*(s-1) != 'e' && *(s-1) != 'E') return false;
77+
} else return false;
78+
}
79+
while (*s == ' ') ++s;
80+
return *s == '\0';
81+
}
6082
};

0 commit comments

Comments
 (0)
0