题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
#include <iostream> #include <istream> #include <sstream> #include <string> #include<bits/stdc++.h> #include <regex> #include<cstring> #include <bitset> #include <stdlib.h> #include <vector> using namespace std; bool judge_ip(string ip) { string n; int number; istringstream ss(ip); int i=0; while(getline(ss,n,'.')) { i++; if(n.empty()) return false; number=stoi(n); if(number>255||number<0) return false; } if(i!=4) return false; return true; } bool judge_mask(string mask) { string n; unsigned number=0; istringstream ss(mask); int i=0; while(getline(ss,n,'.')) { i++; if(n.empty()) return false; number=(number<<8)+stoi(n); } if(!number) return false; number=~number+1; if(number==1) return false; if(number&(number-1)) return false; if(i!=4) return false; return true; } bool judge_private(string ip) { string n; int number; istringstream ss(ip); int i=0; vector<int> v(4,0); while(getline(ss,n,'.')) { if(n.empty()) return false; number=stoi(n); if(number>255||number<0) return false; v[i]=number; i++; } if(i!=4) return false; if(v[0]==10) return true; else if(v[0]==172&&v[1]>=16&&v[1]<=31) return true; else if(v[0]==192&&v[1]==168) return true; return false; } int main() { string line; string ip,mask; int a=0,b=0,c=0,d=0,e=0; int err=0,pri=0; while(getline(cin,line)) { int pos=line.find('~'); ip=line.substr(0,pos); mask=line.substr(pos+1,line.size()); string head=ip.substr(0,ip.find('.')); if(stoi(head)==0||stoi(head)==127) ; else if(!judge_mask(mask)) err++; else if(!judge_ip(ip)) err++; else { if(judge_private(ip)) pri++; if(stoi(head)>=1&&stoi(head)<=126) a++; else if(stoi(head)>=128&&stoi(head)<=191) b++; else if(stoi(head)>=192&&stoi(head)<=223) c++; else if(stoi(head)>=224&&stoi(head)<=239) d++; else if(stoi(head)>=240&&stoi(head)<=255) e++; } } cout<<a<<" "<<b<<" "<<c<<" "<<d<<" "<<e<<" "<<err<<" "<<pri; } // 64 位输出请用 printf("%lld")