Last active
December 26, 2015 05:29
-
-
Save eclipselu/7101050 to your computer and use it in GitHub Desktop.
LeetCode: Valid Number http://oj.leetcode.com/problems/valid-number/
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
/** | |
* determines whether a string is numeric | |
* LeetCode: http://oj.leetcode.com/problems/valid-number/ | |
*/ | |
class Solution { | |
public: | |
bool isSign(const char c) { | |
return c == '-' || c == '+'; | |
} | |
bool isInt(const char *s, int l, int h, bool sign=true) { | |
if (sign && isSign(s[l])) l++; | |
if (l > h) | |
return false; | |
for (int i = l; i <= h; i++) { | |
if (!isdigit(s[i])) | |
return false; | |
} | |
return true; | |
} | |
bool isFloat(const char *s, int l, int h, bool sign=true) { | |
if (sign && isSign(s[l])) l++; | |
int idx = -1; | |
for (int i = l; i <= h; i++) { | |
if (s[i] == '.') { | |
idx = i; | |
break; | |
} | |
} | |
if (idx >= 0) { | |
int hm = idx - 1; | |
int lm = idx + 1; | |
if (l > hm) | |
return isInt(s, lm, h, false); // .123 | |
else if (lm > h) | |
return isInt(s, l, hm); // 12. | |
else | |
return isInt(s, l, hm) && isInt(s, lm, h, false); //12.23 | |
} | |
} | |
bool isHex(const char *s, int l, int h) { | |
if (isSign(s[l])) l++; | |
int len = h - l + 1; | |
if (len>2 && s[l] == '0' && (s[l+1] == 'x' || s[l+1] == 'X')) { | |
for (int i = l + 2; i <= h; i++) { | |
if (!isxdigit(s[i])) | |
return false; | |
} | |
return true; | |
} | |
else | |
return false; | |
} | |
bool isSci(const char *s, int l, int h) { | |
if (isSign(s[l])) l++; | |
int idx = -1; | |
for (int i = l; i <= h; i++) { | |
if (s[i] == 'e' || s[i] == 'E') { | |
idx = i; | |
break; | |
} | |
} | |
if (idx >= 0) { | |
int hm = idx - 1; | |
int lm = idx + 1; | |
return (isFloat(s, l, hm) || isInt(s, l, hm)) && isInt(s, lm, h); | |
} | |
else | |
return false; | |
} | |
bool isNumber(const char *s, int l, int h) { | |
return isInt(s, l, h) || isFloat(s, l, h) || | |
isHex(s, l, h) || isSci(s, l, h); | |
} | |
bool isNumber(const char *s) { | |
// Note: The Solution object is instantiated only once and is reused by each test case. | |
int l = 0, h = strlen(s) - 1; | |
// remove spaces | |
while (s[l] == ' ') l++; | |
while (s[h] == ' ') h--; | |
return isNumber(s, l, h); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment