题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
#include <iostream> #include <string> #include <bitset> #include <math.h> using namespace std; typedef long long int ll; int a = 0, b = 0, c = 0, d = 0, e = 0, err = 0, p = 0; bool ziwangyanma(int z[]) { //按位取反加一后正好为2^n则为正确掩码 //在十进制下就是2^(n+1)-X正好是2^i unsigned int ipy = 0; ipy = z[3] + z[2] * 256 + z[1] * 65536 + z[0] * 16777216; ipy = 4294967296 - ipy; for (int i = 1; i < 32; ++i) { if (ipy - (int)pow(2, i) == 0) { return true; } } err++; return false; } int main() { cin.tie(0); cout.tie(0); ios::sync_with_stdio(0); string ip_input; here: while (getline(cin, ip_input)) { if (ip_input.empty())break; int ip[4] = { 0, 0, 0, 0 }; // IP地址 int ipy[4] = { 0, 0, 0, 0 }; // 掩码地址 string temp[8]; for (int i = 0, j = 0; i < ip_input.length(); i++) { if (ip_input[i] != '.' && ip_input[i] != '~') { temp[j] += ip_input[i]; } else j++; } for (int i = 0, m = 0, n = 0; i < 8; i++) { if (temp[i].size() == 0) { err++; goto here; } else { if (i <= 3) {// IP存放 ip[m] = stoi(temp[i]); m++; } else { // 掩码存放 ipy[n] = stoi(temp[i]); n++; } } } if (ip[0] == 0 || ip[0] == 127) { goto here; } //先看子网掩码 if (ziwangyanma(ipy)) { //IP可忽略错误 for (int i = 0; i < 4; i++) { if (ip[i] < 0 || ip[i] > 255) { err++; goto here; } } //A~E统计 if (ip[0] >= 1 && ip[0] <= 126) { a++; if (ip[0] == 10)p++; } else if (ip[0] >= 128 && ip[0] <= 191) { b++; if (ip[0] == 172 && ip[1] >= 16 && ip[1] <= 31)p++; } else if (ip[0] >= 192 && ip[0] <= 223) { c++; if (ip[1] == 168)p++; } else if (ip[0] >= 224 && ip[0] <= 239) { d++; } else if (ip[0] >= 240 && ip[0] <= 255) { e++; } } } cout << a << ' ' << b << ' ' << c << ' ' << d << ' ' << e << ' ' << err << ' ' << p; return 0; }
就是很多判断语句的一个算法,也没想出其他新鲜的操作了。
小草神的编程日记 文章被收录于专栏
学习编程两年半,希望大家多多关照指点