题目:合法IP
这道题是“判断两个IP是否是同一子网”的子问题,可以用后者的segment函数即可解决,后面的问题详见另一篇博文:点击打开链接http://blog.csdn.net/yiqiwangxi/article/details/47361311
我写的代码比较简单,只考虑了IP中每8位的范围是否是0-255,其他的情况,比如不能包含空格,大家可自行修改。
#include<iostream>
#include<string>
using namespace std;
int segment(string s);
int main()
{
string s;
cin>>s;
int flag;
flag=segment(s);
if(flag)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
//system("pause");
return 0;
}
int segment(string s)
{
int pos=0;
int i=0;
int tmpip;
while((pos=s.find_first_of('.'))!=-1&&i<4)
{
string tmp(s.begin(),s.begin()+pos);
tmpip=atoi(tmp.c_str());
s.erase(s.begin(),s.begin()+pos+1);
if (tmpip<0||tmpip>255)
return 0;
}
tmpip=atoi(s.c_str());
if(tmpip<0||tmpip>255)
return 0;
return 1;
}