题解 | #识别有效的IP地址和掩码并进行分类统计#
坐标移动
http://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
注意那个SB条件://类似于【0...】和【127...】的IP地址不属于上述输入的任意一类,也不属于不合法ip地址,计数时请忽略
#include<bits/stdc++.h>
using namespace std;
vector<string> spilt(string strIn,char c)
{
vector<string> vecOut;
for(int i=0;i<strIn.size();i++)
{
string strTmp = "";
while(strIn[i]!=c && i<strIn.size())
{
strTmp += strIn[i];
i++;
}
vecOut.emplace_back(strTmp);
}
return vecOut;
}
bool isMask(string strIn);
bool isIp(vector<string> vecIp);
bool isPrivate(vector<string> vecIp);
int main()
{
string strIn;
int A=0,B=0,C=0,D=0,E=0,err=0,priva=0;
while(getline(cin,strIn))
{
int idx = strIn.find('~');
string ip = strIn.substr(0,idx);
string mask = strIn.substr(idx+1);
vector<string> vecIp = spilt(ip,'.');
//类似于【0.*.*.*】和【127.*.*.*】的IP地址不属于上述输入的任意一类,也不属于不合法ip地址,计数时请忽略
//沙比出题人!nmsl 浪费好多时间
int first = stoi(vecIp[0]);
if(first==0 || first==127)
continue;
//先判断子网
if(isMask(mask))
{
//再判断ip
if(!isIp(vecIp))
{
err++;
continue;
}
if(isPrivate(vecIp))
priva++; //私有和后面不冲突
if(first > 0 && first <127) A++;
else if(first > 127 && first <192) B++;
else if(first > 191 && first <224) C++;
else if(first > 223 && first <240) D++;
else if(first > 239 && first <256) E++;
}
else
err++;
}
cout<<A<<' '<<B<<' '<<C<<' '<<D<<' '<<E<<' '<<err<<' '<<priva;
}
bool isMask(string strIn)
{
vector<string> vecMask = spilt(strIn,'.');
unsigned int mask32 =0; //子网掩码32位
for(int i=0;i<vecMask.size();i++)
{
unsigned int numi = (unsigned)stoi(vecMask[i]);
if(numi > 255)
return false;
mask32 = (mask32<<8) + numi;
}
if(mask32==0 || ~mask32 ==0) return false; //全0或者全1
//取反+1 然后与-1的值与运算
mask32 = ~mask32 +1;
if(mask32 & (mask32-1)) return false;
else return true;
}
bool isIp(vector<string> vecIp)
{
if(vecIp.size()!=4) return false; //字段不为4
for(string& strTmp:vecIp)
if(strTmp.empty() || stoi(strTmp)>255)
return false;
return true;
}
bool isPrivate(vector<string> vecIp)
{
int first = stoi(vecIp[0]);
int second = stoi(vecIp[1]);
if(first==10 || (first==172 && second>15 && second<32) || (first==192 && second==168) )
return true;
else
return false;
}