题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
http://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
xdm 注意这句话 !!!!!!! 只能过80%,试了几个小时
类似于【0...】和【127...】的IP地址不属于上述输入的任意一类,也不属于不合法ip地址,计数时请忽略
#include<sstream>
using namespace std;
bool Analysis(string& address, vector<int>& res)
{
int start = 0;
stringstream s;
int d1 = address.find('.');
int d2 = address.find('.',d1 + 1);
int d3 = address.find('.',d2 + 1);
vector<string>strs(4);
strs[0] = address.substr(0,d1);
strs[1] = address.substr(d1 + 1,d2 - d1 - 1);
strs[2] = address.substr(d2 + 1,d3 - d2 - 1);
strs[3] = address.substr(d3 + 1);
for(auto str : strs)
{
if(str.size() == 0)return false;
}
for(int i = 0;i < 4;i++)
{
int num;
s.clear();
s << strs[i];
s >> num;
if(num < 0 || num > 255)return false;
res[i] = num;
}
return true;
}
bool isValid(vector<int> vec)
{
if(vec[0] == 0 && vec[1] == 0 && vec[2] == 0 && vec[3] == 0)return false;
if(vec[0] == 255 && vec[1] == 255 && vec[2] == 255 && vec[3] == 255)return false;
int flag = 1;
for(int i = 0;i < 4;i++)
{
int tmp = vec[i];
if(flag == 1 && tmp < 255)
{
if(tmp != 254 && tmp != 252 && tmp != 248 && tmp != 240 && tmp != 224 && tmp != 192 && tmp != 128 && tmp != 0)
{
return false;
}
flag = 0;
}
else if(flag == 0 && tmp != 0)
{
return false;
}
}
return true;
}
int main()
{
string str;
int A,B,C,D,E,errors,private_ip;
A = B = C = D = E = errors = private_ip = 0;
while(cin >> str)
{
int pos = str.find('~');
string ip = str.substr(0,pos);
string code = str.substr(pos + 1);
//解析ip和子网掩码
vector<int> Ip(4);
vector<int> Code(4);
//判断地址是否合法
if((!Analysis(ip, Ip)) || (!Analysis(code,Code)) || (!isValid(Code)))
{
if(Ip[0] == 0 || Ip[0] == 127)continue;
errors++;
}
else
{
//首先判断ABCDE
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++;
//再判断是否为私网ip
if((Ip[0] == 10) || (Ip[0] == 172 && (Ip[1] >= 16 && Ip[1] <= 31)) || (Ip[0] == 192 && Ip[1] == 168))
{
private_ip++;
}
}
}
cout << A << " " << B << " " << C << " " << D << " " << E << " " << errors << " " << private_ip;
return 0;
}