题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
http://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
#include<iostream> #include<string> #include<vector> using namespace std; vector<int> ipValue(const string& str); bool ipIsValid(const vector<int>& p); bool ipIsValidMask(const vector<int>& p); int ipIsSame(const vector<int>& p1, const vector<int>& p2, const vector<int>& m); int main(){ string ip1; string ip2; string mask; while(cin >> mask >> ip1 >> ip2){ vector<int>p1 = ipValue(ip1); vector<int>p2 = ipValue(ip2); vector<int>m = ipValue(mask); if(!ipIsValid(p1) || !ipIsValid(p2) || !ipIsValidMask(m)){ //cout <<ipIsValidMask(m) << endl; cout << 1 << endl; }else{ cout << ipIsSame(p1, p2, m) << endl; } } return 0; } vector<int> ipValue(const string& str){ int i = 0; int num = 0; vector<int> p; while(i < str.size()){ if(str[i] == '.'){ p.push_back(num); num = 0; }else if(i == str.size() - 1){ num = num * 10 + (str[i] - '0'); p.push_back(num); }else{ num = num * 10 + (str[i] - '0'); } i++; } return p; } bool ipIsValid(const vector<int>& p){ for(int i = 0; i < p.size(); ++i){ if(p[i] > 255 || p[i] < 0) return false; } return true; } bool ipIsValidMask(const vector<int>& p){ for(int i = 0; i < p.size(); ++i){ if(p[i] > 255 || p[i] < 0) return false; if(p[i]>0&&p[i-1]<255&&i>0) return false; } return true; } int ipIsSame(const vector<int>& p1, const vector<int>& p2, const vector<int>& m){ int flag = 0; for(int i = 0; i < p1.size(); ++i){ int a = p1[i] & m[i]; int b = p2[i] & m[i]; if(a != b){ return 2; } } return 0; }