题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
http://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
#include<string>
#include<vector>
using namespace std;
class Solution{
public:
int get_ans(string &mask,string IP1,string IP2){
vector<int> mask_4(4),IP1_4(4),IP2_4(4);
// cout<<mask<<' '<<IP1<<' '<<IP2<<endl;
//以下数值化子网掩码,IP1和IP2
int i=0,index=0;
while(index<4){
mask_4[index++]=get_num(mask,i);
}
i=0,index=0;
while(index<4){
IP1_4[index++]=get_num(IP1,i);
}
i=0,index=0;
while(index<4){
IP2_4[index++]=get_num(IP2,i);
}
//判断
int res=0;
for(int i=0;i<4;i++){
//超出255范围
if(mask_4[i]>255||IP1_4[i]>255||IP2_4[i]>255){
return 1;
}
//子网掩码到此开始后面是0
if(mask_4[i]!=255){
if(mask_4[i]!=0&&mask_4[i]!=0x80&&mask_4[i]!=0xC0&&mask_4[i]!=0xE0
&&mask_4[i]!=0xF0&&mask_4[i]!=0xF8&&mask_4[i]!=0xFC&&mask_4[i]!=0xFE){
return 1;
}
for(int j=i+1;j<4;j++){
if(mask_4[j]!=0){
return 1;
}
}
}
//cout<<(IP1_4[i]&mask_4[i])<<' '<<(IP2_4[i]&mask_4[i])<<endl;
//判断两IP是或否为同一网络的子网
if((IP1_4[i]&mask_4[i])!=(IP2_4[i]&mask_4[i])){
res=2;
}
}
return res;
}
int get_num(string &s,int &i){
int res=0;
while(i<s.size()&&s[i]!='.'){
//特殊字符,返回256
if(s[i]<'0'||s[i]>'9'){
return 256;
}
res*=10;
res+=s[i++]-'0';
}
i++;
return res;
}
};
int main(){
string mask,IP1,IP2;
Solution sol;
while(cin>>mask>>IP1>>IP2){
cout<<sol.get_ans(mask,IP1,IP2)<<endl;
}
return 0;
}