Created
February 2, 2013 03:07
-
-
Save pdu/4695965 to your computer and use it in GitHub Desktop.
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. http://leetcode.com/onlinejudge#question_65
This file contains hidden or 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
| class Solution { | |
| public: | |
| bool isInt(const char* s, int len) { | |
| if (len == 0) | |
| return false; | |
| int st = 0; | |
| if (s[0] == '+' || s[0] == '-') | |
| st = 1; | |
| if (st == len) | |
| return false; | |
| for (int i = st; i < len; ++i) | |
| if (s[i] >= '0' && s[i] <= '9') | |
| ; | |
| else | |
| return false; | |
| return true; | |
| } | |
| bool isNumber__(const char* s, int len) { | |
| int dot_pos = -1; | |
| for (int i = 0; i < len; ++i) | |
| if (s[i] == '.') { | |
| if (dot_pos == -1) | |
| dot_pos = i; | |
| else | |
| return false; | |
| } | |
| if (dot_pos == -1) | |
| return isInt(s, len); | |
| else { | |
| if (len == 1) | |
| return false; | |
| if (dot_pos != len - 1) { | |
| if (s[dot_pos + 1] >= '0' && s[dot_pos + 1] <= '9') { | |
| if (dot_pos != len - 2 && !isInt(s + dot_pos + 1, len - dot_pos - 1)) | |
| return false; | |
| } | |
| else | |
| return false; | |
| } | |
| if (dot_pos != 0) { | |
| if (dot_pos == 1 && (s[0] == '+' || s[0] == '-')) { | |
| if (len == 2) | |
| return false; | |
| else | |
| return true; | |
| } | |
| if (!isInt(s, dot_pos)) | |
| return false; | |
| } | |
| return true; | |
| } | |
| } | |
| bool isNumber_(const char* s, int len) { | |
| int e_pos = -1; | |
| for (int i = 0; i < len; ++i) | |
| if (s[i] == 'e') { | |
| if (e_pos == -1) | |
| e_pos = i; | |
| else | |
| return false; | |
| } | |
| if (e_pos == 0 || e_pos == len - 1) | |
| return false; | |
| if (e_pos != -1) | |
| return isNumber__(s, e_pos) && isInt(s + e_pos + 1, len - e_pos - 1); | |
| else | |
| return isNumber__(s, len); | |
| } | |
| bool isNumber(const char *s) { | |
| int len = strlen(s); | |
| int end = len; | |
| for (int i = len - 1; i >= 0; --i) | |
| if (s[i] == ' ' || s[i] == '\t') | |
| end = i; | |
| else | |
| break; | |
| for (int i = 0; s[i] != '\0'; ++i) | |
| if (s[i] != ' ' && s[i] != '\t') | |
| return isNumber_(s + i, end - i); | |
| return false; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment