题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
#include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> using namespace std; int main() { vector<string> a; string str; int len = 0; int A = 0,B = 0,C = 0, D = 0, E = 0, er = 0, pri = 0; while(getline(cin,str)) { if(str!="") { a.push_back(str); len++; } } for(int i = 0; i < len; i++) { stringstream ss; ss<<a[i];//一行输入 vector<string> s;//存储一行中的IP和子网掩码;s[0]-ip;s[1]-子网掩码 vector<string> ip;//存储ip4个字段; vector<string> subnet;//存储子网掩码四个字段 string temp; while (getline(ss,temp,'~'))//用~隔开 { s.push_back(temp); } stringstream ss1,ss2; ss1<<s[0]; ss2<<s[1]; string temp1,temp2; while(getline(ss1,temp1,'.')) { ip.push_back(temp1); } while(getline(ss2,temp2,'.')) { subnet.push_back(temp2); } //ip或者掩码字段长度有误 if(ip.size()!=4||subnet.size()!=4) { er ++; continue; } //判断是否为0或者127开头 if(ip[0].size() == 1&&ip[0] == "0") { continue; } if(ip[0].size()==3&&ip[0]=="127") { continue; } //判断ip和子网掩码是否合法 bool error = true; vector<int> subnetInt(32,0);//将子网掩码转换为二进制 for(int j = 0; j < 4; j++) { int num = 0; if(ip[j] == "") { error = false; break; } if(ip[j].size() > 3) { error = false; break; } if(ip[j].size() == 3) { num = (ip[j][0]-48)*100+(ip[j][1]-48)*10+ip[j][2]-48; if(num>255) { error = false; break; } } int tempInt = 0; if(subnet[j].size()==3) { tempInt = (subnet[j][0]-48)*100+(subnet[j][1]-48)*10+subnet[j][2]-48; } if(subnet[j].size()==2) { tempInt = (subnet[j][0]-48)*10+subnet[j][1]-48; } if(subnet[j].size()==1) { tempInt = subnet[j][0]-48; } int count = (j+1)*8 -1 ; if(tempInt != 0) { int tem = tempInt; while(tem/2!=0)//转为二进制 { int n = tem%2; subnetInt[count] = n; count--; tem/=2; } subnetInt[count] = 1; } // for(auto i:subnet) // cout<<i<<" "; int flag = 1; int numOf1 = 0; int rflag = 1; int numOf0 = 0; for(int t = 0; t <32; t++) { if(subnetInt[t]==1&&flag == 1) { numOf1 ++; } if(subnetInt[t] == 0) { flag = 0; break; } } for(int t = 31; t >=0; t--) { if(subnetInt[t]==0&&rflag == 1) { numOf0 ++; } if(subnetInt[t] == 1) { rflag = 0; break; } } if(numOf0==32||numOf1==32||numOf0+numOf1!=32) { error = false; } } if(!error) { er++; continue; } int ipInt = 0; int ipInt2 = 0; if(ip[0].size() == 1) { ipInt = ip[0][0]-48; } if(ip[0].size() == 2) { ipInt = (ip[0][0]-48)*10+ip[0][1]-48;; } if(ip[0].size() == 3) { ipInt = (ip[0][0]-48)*100+(ip[0][1]-48)*10+ip[0][2]-48;; } if(ip[1].size() == 1) { ipInt2 = ip[1][0]-48; } if(ip[1].size() == 2) { ipInt2 = (ip[1][0]-48)*10+ip[1][1]-48;; } if(ip[1].size() == 3) { ipInt2 = (ip[1][0]-48)*100+(ip[1][1]-48)*10+ip[1][2]-48;; } if(ipInt<127) A++; if(ipInt>127&&ipInt<192) B++; if(ipInt>191&&ipInt<224) C++; if(ipInt>223&&ipInt<240) D++; if(ipInt>239) E++; if(ipInt == 10) pri++; if(ipInt == 172&&ipInt2>15&&ipInt2<32) pri++; if(ipInt == 192&&ipInt2==168) pri++; } cout<<A<<" "<<B<<" "<<C<<" "<<D<<" "<<E<<" "<<er<<" "<<pri; } // 64 位输出请用 printf("%lld")