题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
#include <iostream> #include <string> using namespace std; #include<vector> bool maskvalid(vector<int> mask){ unsigned int maskvalue = 0; for(int i =0;i<4;i++){ maskvalue = (maskvalue<<8)+mask[i]; } bool seenZero = false; for(int i = 31;i>=0;i--){ if(maskvalue & (1<<i)){ if(seenZero) return false; } else { seenZero = true;//如果当前位不为1,就把该标记变成true,之后的位再出现1就会return false } } return true; } bool typevalid(vector<int> type){ for(int num :type){ if(num<0||num>255){ return false; } } return true; } vector<int> ipValid(vector<int>ip,vector<int>mask){ vector<int> results(4); for(int i =0;i<4;i++){ results[i] = ip[i]& mask[i]; } return results; } int main() { vector<int> mask(4,0); vector<int> ip1(4,0); vector<int> ip2(4,0); char c; cin>>mask[0]>>c>>mask[1]>>c>>mask[2]>>c>>mask[3]; cin>>ip1[0]>>c>>ip1[1]>>c>>ip1[2]>>c>>ip1[3]; cin>>ip2[0]>>c>>ip2[1]>>c>>ip2[2]>>c>>ip2[3]; if(!typevalid(mask)||!typevalid(ip1)||!typevalid(ip2)||!maskvalid(mask)){ cout<<1<<endl; return 0; } if(ipValid(ip1, mask)==ipValid(ip2, mask)){ cout<<0<<endl; }else { cout<<2<<endl; } return 0; } // 64 位输出请用 printf("%lld")