#include<iostream>
#include<string>
#include<string.h>
#include<stdlib.h>
#include<vector>
using namespace std;
//注意:当字符串为空时,也会返回一个空字符串
void split(string& s, vector<string> &ret)
{
size_t last = 0;
string delim(".");
size_t index=s.find_first_of(delim,last);
while (index!=std::string::npos)
{
ret.push_back(s.substr(last,index-last));
last=index+1;
index=s.find_first_of(delim,last);
}
if (index-last>0)
{
ret.push_back(s.substr(last,index-last));
}
}
bool getNumVector(string mask,vector<int> &m)
{
vector<string> ret;
int tempt;
split(mask,ret);
if(ret.size() != 4)
return false;
else
{
vector<string>::iterator iter = ret.begin();
for(;iter != ret.end();++iter)
{
tempt = atoi(iter->c_str());
if(tempt<0||tempt>255)
return false;
else
m.push_back(tempt);
}
}
}
bool isSameNet(vector<int> &m,vector<int> &ipnum1,vector<int> &ipnum2)
{
bool flag = true;
int size = 4;
vector<int>::iterator iter = m.begin();
vector<int>::iterator ipter1 = ipnum1.begin();
vector<int>::iterator ipter2 = ipnum2.begin();
while(size--)
{
//cout<<"mask"<<size<<*iter<<endl;
//cout<<"ip1"<<size<<*ipter1<<endl;
//cout<<"ip2"<<size<<*ipter2<<endl;
if(((*iter)&(*ipter1)) == ((*iter)&(*ipter2)))
{
++iter;
++ipter1;
++ipter2;
}
else
{
flag = false;
break;
}
}
return flag;
}
int checkNetSegment(string mask,string ip1,string ip2)
{
vector<int> m,ipnum1,ipnum2;
if(getNumVector(mask,m)&&getNumVector(ip1,ipnum1)&&getNumVector(ip2,ipnum2))
{
if(isSameNet(m,ipnum1,ipnum2))
return 0;
else
return 2;
}
else
return 1;
}
int main()
{
int result;
string mask,ip1,ip2;
while(cin>>mask>>ip1>>ip2)
cout<<checkNetSegment(mask,ip1,ip2)<<endl;
return 0;
}
华为oj 判断两个ip是否属于同一子网
最新推荐文章于 2022-03-21 20:39:16 发布