#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <fstream>
using namespace std;
string binary(const unsigned int val,string s)
{
for(int i = 7; i >= 0; i--)
{
if(val & (1 << i))
s.push_back('1');
else
s.push_back('0');
}
return s;
}
//二进制IP转换成十进制IP
string Todec(string binaryIP)
{
stringstream s;
string temp;
string dec;
for(int i=0;i<4;i++)//4组8位二进制码
{
for(int j=9*i;j<(9*i+8);j++)
{
s<<binaryIP[j];
}
s>>temp;
int number=stoi(temp,nullptr,2);
s.clear();
s.str("");
s<<number;
string tempdec;
s>>tempdec;
dec+=tempdec+".";
s.clear();
s.str("");
}
dec.pop_back();
return dec;
}
string ToBinary(string ip)//生成二进制的IP码
{
stringstream s;
string binaryIP;
for(int i=0;i<ip.length();i++)
{
if(ip[i]!='.')
s<<ip[i];
if(ip[i]=='.'||(i==ip.length()-1))
{
int a=0;
s>>a;
string binary8;
binary8=binary(a,binary8);
//两个函数都是必要的,一个是清空s中的内容,一个是重置s的状态标志位
s.str("");
s.clear();
if(binaryIP.size()==0)
binaryIP+=binary8;
else
binaryIP+="|"+binary8;
}
}
return binaryIP;
}
//返回比较后的二进制码并且传引用返回不相同位数
string compare(string binary1,string binary2,int &n)//1为当前最小串,2为新的值
{
int countpoint=0;
for(int i=0;i<binary1.size();i++)
{
if(binary1[i]!=binary2[i])
{
for(int j=i;j<binary1.size();j++)
{
if(binary1[j]!='|')
binary1[j]='0';
else countpoint++;
}
if((binary1.length()-i)>n)
n=binary1.length()-i-countpoint;
break;
}
}
return binary1;
}
int main()
{
int n;
while(cin>>n)
{
string temp;//保存目前的最小ip
bool first=1;
int notSame=0;//不相同的位数
while(n--)
{
string ip;
cin>>ip;
string binaryIP;
binaryIP=ToBinary(ip);
if(first==1)
{
temp=binaryIP;
first=0;
}
else if(first==0)
{
int ¬SameCopy=notSame;
temp=compare(temp,binaryIP,notSameCopy);
}
}
string answer;
answer=Todec(temp);
cout<<answer<<endl;
string answer2;
for(int i=0;i<4;i++)
{
for(int j=8*i;j<(8*i+8);j++)
{
if(j>=(32-notSame))
answer2.push_back('0');
else
answer2.push_back('1');
}
if(i!=3)
answer2.push_back('|');
}
cout<<Todec(answer2)<<endl;
}
}
习题4-5 IP网络 UVa 1590
最新推荐文章于 2019-02-20 22:16:00 发布