题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
http://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
来个组合套装
#include<iostream> #include<sstream> #include<vector> #include<bitset> using namespace std; enum IpType { Code, Ip, Route }; bool isValidString(string str, unsigned int& num, IpType type){ for(auto& item:str){ if(item=='.'){ item=' '; } } vector<int> nums; stringstream record(str); unsigned int temp; while(record>>temp) nums.push_back(temp); if(nums.size()!=4) return false; for(auto item:nums) if(item < 0|| item > 255) return false; num = nums[0]<<24|nums[1]<<16|nums[2]<<8|nums[3]<<0; if(type == Code){ bitset<32> b(num); std::string strMask = b.to_string(); if(strMask.find("01")!=strMask.npos) return false; } return true; } int main(){ string temp1, temp2, temp3; while(cin>>temp1>>temp2>>temp3){ unsigned int num1, num2, num3; if(isValidString(temp1, num1, Code) && isValidString(temp2, num2, Ip) && isValidString(temp3, num3, Route)){ if((num1&num3)==(num2&num1)) cout<<"0"<<endl; else cout<<"2"<<endl; }else cout<<"1"<<endl; } }