Created
May 14, 2015 09:30
-
-
Save qi7chen/f2b5644a1e872b6cdf39 to your computer and use it in GitHub Desktop.
Validate if a given string is numeric
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Validate if a given string is numeric. | |
// https://leetcode.com/problems/valid-number/ | |
bool isNumber(const char* s) | |
{ | |
if (s == NULL) | |
{ | |
return false; | |
} | |
const char* begin = s; | |
// skip whitespace | |
while (*begin == ' ' || *begin == '\t') | |
{ | |
begin++; | |
} | |
int num = 0; | |
int dot = 0; | |
int exp = 0; | |
int blank = 0; | |
int ch = 0; | |
int pre = 0; | |
while ((ch = *begin++)) | |
{ | |
switch (ch) | |
{ | |
case '0': | |
case '1': | |
case '2': | |
case '3': | |
case '4': | |
case '5': | |
case '6': | |
case '7': | |
case '8': | |
case '9': | |
if (pre == ' ') | |
return false; | |
num++; | |
break; | |
case '+': | |
case '-': | |
if (pre && !(pre == 'e' || pre == 'E') || pre == ' ') | |
return false; | |
break; | |
case '.': | |
if (dot || exp || pre == ' ') | |
return false; | |
dot = 1; | |
break; | |
case 'e': | |
case 'E': | |
if (num == 0 || exp || pre == ' ') | |
return false; | |
exp = num; | |
break; | |
case ' ': | |
case '\t': | |
break; | |
default: | |
return false; | |
} | |
pre = ch; | |
} | |
if ((num <= exp) || (dot && num == 0)) | |
return false; | |
return num > 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment