[编程题]识别有效的IP地址和掩码并进行分类统计
识别有效的IP地址和掩码并进行分类统计
http://www.nowcoder.com/questionTerminal/de538edd6f7e4bc3a5689723a7435682
#include<bits/stdc++.h> #include<vector> using namespace std; int ip[4], ipy[4]; string s; string s1, s2; int A = 0,B = 0,C = 0,D = 0,E = 0,S = 0,EIP = 0; void check() { int index = 0; int sum = 0; for(int i = 0; i < s1.size(); i++) { if(i == 0 && s1[i] == '.') { ip[0] = -1; index++; } else if(s1[i] == '.' && s1[i - 1] != '.') { ip[index] = sum; sum = 0; index++; } else if(s1[i] == '.' && s1[i - 1] == '.') { ip[index] = -1; index++; } else { sum = sum * 10 + s1[i] - '0'; } if(i == s1.size() - 1) ip[index] = sum; } int index2 = 0; int sum2 = 0; for(int i = 0; i < s2.size(); i++) { if(i == 0 && s2[i] == '.') { ipy[0] = -1; index2++; } else if(s2[i] == '.' && s2[i - 1] != '.') { ipy[index2] = sum2; sum2 = 0; index2++; } else if(s2[i] == '.' && s2[i - 1] == '.') { ipy[index2] = -1; index2++; } else { sum2 = sum2 * 10 + s2[i] - '0'; } if(i == s2.size() - 1) ipy[index2] = sum2; } } void add() { for(int i = 0; i < 4; i++) { if(ip[i] == -1 || ip[i] > 255) { EIP++; return; } } if((ipy[0] == 255 && ipy[1] == 255 && ipy[2] == 255 && ipy[3] == 255) || (ipy[0] == 0 && ipy[1] == 0 && ipy[2] == 0 && ipy[3] == 0)) { EIP++; return; } for(int i = 0; i < 4; i++) { if(ipy[i] == -1 || ipy[i] > 255) { EIP++; return; } } for(int i = 3; i >= 0; i--) { if(ipy[i] != 0) { for(int j = 0; j < i; j++) { if(ipy[j] != 255) { EIP++; return; } } if(ipy[i] != 255 && ipy[i] != 254 && ipy[i] != 252 && ipy[i] != 248 && ipy[i] != 240 && ipy[i] != 224 && ipy[i] != 192 && ipy[i] != 128) { EIP++; return; } } if(i == 0 && ipy[0] == 0) { EIP++; return; } } if(ip[0] == 0 || ip[0] == 127) return; if(ip[0] >= 1 && ip[0] <= 126) A++; if(ip[0] >= 128 && ip[0] <= 191) B++; if(ip[0] >= 192 && ip[0] <= 223) C++; if(ip[0] >= 224 && ip[0] <= 239) D++; if(ip[0] >= 240 && ip[0] <= 255) E++; if(ip[0] == 10) S++; if(ip[0] == 172 && ip[1] >= 16 && ip[1] <= 31) S++; if(ip[0] == 192 && ip[1] == 168) S++; } int main() { //freopen("1.txt", "r", stdin); while(cin >> s) { s2 = s.substr(s.find('~') + 1, s.size() - s.find('~') - 1); s1 = s.substr(0, s.find('~')); //cout << s1 << endl; //cout << s2 << endl; check(); // for(int i = 0; i <4; i++) { // cout << ip[i] << "."; // } // cout << endl; // for(int i = 0; i <4; i++) { // cout << ipy[i] << "."; // } // cout <<endl; add(); } cout << A << " " << B << " " << C << " " << D << " " << E << " " << EIP << " " << S << endl; return 0; }