HJ18 识别有效的IP地址和掩码并进行分类统计
HJ18 识别有效的IP地址和掩码并进行分类统计
#include #include #include #include // #define DEBUG#ifdef DEBUG#include #endifusing namespace std;class HJ18 {private: int a, b, c, d, e, x, p; static unsigned str2unsigned(std::string s) { unsigned m = 0; for (int i = 0; i < s.size(); i++) { m = 10 * m + s.at(i) - '0'; } return m; } static bool isValidMask(unsigned mask) { // 二进制下全是1或者全是0均为非法子网掩码 if (0 == mask || mask == 0xffffffff) { return false; } int i; for (i = 31; i >=0; i--) { if ((mask & (1<= 0) { if ((mask & (1<1 } } return true; }public: HJ18() { this->a = this->b = this->c = this->d = this->e = this->x = this->p = 0; } HJ18 add(string input) { vector vs = split(std::move(input), '~');#ifdef DEBUG cout.setf(ios::showbase); std::cout << "ip=" <b += 1; if (fb == 172 && (16<=nb && nb < 32)) { this->p += 1; } // std::cout << "B class\n"; } else if (fb < 224) { this->c += 1; // std::cout << "C class " << "fb="<p += 1; } } else if (fb < 240) { this->d += 1; } else { this->e += 1; } return *this; } string toString() const { stringstream ss; ss << a << " "<< b << " " << c << " " << d << " " << e << " "<< x << " " << p; string s = ss.str(); ss.clear(); return s; } static unsigned int ip2long(string s) { vector vs = split(std::move(s), '.'); unsigned int ip = 0; unsigned u; for (auto & v : vs) { if (v.empty()) { throw bad_exception(); } u = str2unsigned(v); if (u < 0 || u > 255) { throw bad_exception(); } ip = (ip << 8) | u; } return ip; } static vector split(string s, char delim) { vector vec; int i; int subLen = 0; int len = s.size(); for (i = 0; i < len; i++) { if (s.at(i) != delim) { subLen += 1; continue; } vec.push_back(s.substr(i-subLen, subLen)); subLen = 0; } vec.push_back(s.substr(i-subLen, subLen)); return vec; }};int main() { HJ18 solution; string line;#ifndef DEBUG while (cin >> line) { solution.add(line); }#else std::ifstream ifs; ifs.open("../input4.txt", std::ios_base::in); if (!ifs.is_open()) { std::cout << "打开../input4.txt失败"; return -2; } int i = 0; while (ifs >> line) { solution.add(line); cout.unsetf(ios::hex); std::cout <<"----------"<<++i<<"-------------\n"; } ifs.close();#endif cout << solution.toString() << endl;}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~