首页 > 代码库 > LeetCode "Valid Number"
LeetCode "Valid Number"
It took me +20 submissions to get AC... Actually the statement is too vague. I would rather ask for requirements f2f.
Apparently the code below can be simplified..
class Solution {public: bool isPureNum(string s, int radix) { if (s.length() > 1 && s[s.length() - 1] == ‘.‘) { s = s.substr(0, s.length() - 1); } int i = 0; while(i < s.length()) { char c = s[i++]; switch(radix) { case 10: if(!(c >= ‘0‘ && c <= ‘9‘)) return false; break; case 16: if(!((c >= ‘0‘ && c <= ‘9‘) || (c >= ‘a‘ && c <= ‘f‘))) return false; break; } } return true; } bool isFloat(string str) { size_t pos = str.find(‘.‘, 0); string s1 = str.substr(0, pos); if(s1.find(‘.‘, 0) != string::npos) return false; string s2 = str.substr(pos + 1, str.length() - pos - 1); if(s2.find(‘.‘, 0) != string::npos) return false; if (s1.empty() && s2.empty()) return false; return isPureNum(s1, 10) && isPureNum(s2, 10); } bool isNumber(const char *s) { int len = strlen(s); if(len == 0) return false; // Trim int il = 0, ir = len - 1; while(*(s + il) == ‘ ‘) il ++; while(*(s + ir) == ‘ ‘) ir --; if(ir < il) return false; // ToLower string str; str.assign(s + il, s + ir + 1); std::transform(str.begin(), str.end(), str.begin(), ::tolower); if(str[0] == ‘-‘ || str[0] == ‘+‘) str = str.substr(1, str.length() - 1); len = str.length(); char c = str[0]; size_t pos1 = str.find(‘e‘, 0); if(pos1 != string::npos) { // 2e10 string s1 = str.substr(0, pos1); if(s1.empty()) return false; if(s1.find(‘e‘, 0) != string::npos) return false; string s2 = str.substr(pos1 + 1, str.length() - pos1 - 1); if(s2.find(‘e‘, 0) != string::npos) return false; if(s2.find(‘.‘, 0) != string::npos) return false; if(s2[0] == ‘-‘ ||s2[0] == ‘+‘) s2 = s2.substr(1, s2.length() - 1); if(s2.empty()) return false; return (isPureNum(s1, 10) || isFloat(s1)) && isPureNum(s2, 10); } else { if(isdigit(c)) { if(len == 1) return true; if(str[1] == ‘x‘) { if(str[0] == ‘0‘) return isPureNum(str.substr(2, str.length() - 2), 16); else return false; } else { size_t pos = str.find(‘.‘, 0); if(pos != string::npos) { // float string s1 = str.substr(0, pos); if(s1.find(‘.‘, 0) != string::npos) return false; string s2 = str.substr(pos + 1, str.length() - pos - 1); if(s2.find(‘.‘, 0) != string::npos) return false; if(s2.find(‘+‘, 0) != string::npos) return false; if(s2.find(‘-‘, 0) != string::npos) return false; if (s1.empty() && s2.empty()) return false; return isPureNum(s1, 10) && isPureNum(s2, 10); } return isPureNum(str, 10); } } else if (c == ‘.‘) // ".123" { string s2 = str.substr(1, str.length() - 1); if(s2.find(‘.‘, 0) != string::npos) return false; if(s2.find(‘ ‘, 0) != string::npos) return false; if(s2.find(‘+‘, 0) != string::npos) return false; if(s2.find(‘-‘, 0) != string::npos) return false; return isNumber(s2.c_str()); } } return false; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。