题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
#include <iostream> #include <string> #include <sstream> #include <vector> #include <regex> using namespace std; vector<string> split(string line,char p); bool isValidIp(string ip); bool isValidMask(string mask); int InClass(string ip); bool isPriIp(string ip); int main(){ string line; int countA=0,countB=0,countC=0,countD=0,countE=0,countErr=0,countPri=0; while(getline(cin,line)){ if (line.empty()) { break; } vector<string> parts; parts = split(line,'~'); if(parts.size()!=2){ countErr++; continue; } if(!isValidIp(parts[0])){ countErr++; continue; } if(stoi(split(parts[0],'.')[0])==127||stoi(split(parts[0],'.')[0])==0) continue; if(!isValidMask(parts[1])){ countErr++; continue; } int classNum = InClass(parts[0]); switch (classNum) { case 1:countA ++;break; case 2:countB ++;break; case 3:countC ++;break; case 4:countD ++;break; case 5:countE ++;break; } if(isPriIp(parts[0])){ countPri++; } } cout<<countA<<" "<<countB<<" "<<countC<<" "<<countD<<" "; cout<<countE<<" "<<countErr<<" "<<countPri<<endl; return 0; } vector<string> split(string line,char p){ stringstream ss(line); string str1; vector<string> parts; while(getline(ss,str1,p)){ parts.push_back(str1); } return parts; } bool isValidIp(string ip){ regex pattern(R"(^((25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])$)"); return regex_match(ip,pattern); } bool isValidMask(string mask){ if(!isValidIp(mask)) return false; vector<string> parts = split(mask,'.'); int maskNum=0; for(int i=0;i<3;i++){ maskNum += stoi(parts[i]); maskNum <<= 8; } maskNum += stoi(parts[3]); if(maskNum==0x00000000||maskNum==0xffffffff) return false; bool foundZero = false; for(int i=31;i>=0;i--){ if((maskNum & (1<<i))==0){ foundZero=true; } else if(foundZero) return false; } return true; } int InClass(string ip){ vector<string> parts; parts = split(ip,'.'); int a= stoi(parts[0]); if(a>=1&&a<=126){ return 1; } if(a>=128&&a<=191){ return 2; } if(a>=192&&a<=223){ return 3; } if(a>=224&&a<=239){ return 4; } if(a>=240&&a<=255){ return 5; } else return 0; } bool isPriIp(string ip){ vector<string> parts; parts = split(ip,'.'); int a= stoi(parts[0]); int b= stoi(parts[1]); if((a==10)||(a==172&&b>=16&&b<=31)||(a==192&&b==168)) return true; else return false; }