题解 | 判断两个IP是否属于同一子网
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
#include <algorithm> #include <iostream> #include <istream> #include <sstream> #include <vector> using namespace std; string toBinary(int n) { string binary; while(n != 0) { binary = n%2 ? '1' + binary : '0' + binary; n = n/2; } string zero(8 - binary.size(), '0'); return zero + binary; } bool youxiaoip(string& ip, string &binaryip) { istringstream iss(ip + '.'); string str; while (getline(iss, str, '.')) { istringstream isss(str); int n; isss >> n; if (n < 0 || n > 255) { return false; } binaryip += toBinary(n); } return true; } bool youxiaoyanma(string& yanma, string &binaryyanma) { istringstream iss(yanma + '.'); string str; while (getline(iss, str, '.')) { istringstream isss(str); int n; isss >> n; if (n < 0 || n > 255) { return false; } binaryyanma += toBinary(n); } auto it = binaryyanma.find_first_of('0'); if(it != string::npos) { string zero = binaryyanma.substr(it); if(count(zero.begin(), zero.end(), '0') != zero.size()) { return false; } } return true; } string yuyunsuan(string &ip, string &yanma) { string res; for(int i = 0; i < ip.size(); i++) { if(ip[i] == '0' || yanma[i] == '0') { res += '0'; } else{ res += '1'; } } return res; } int main() { string yanma, ip1, ip2; while (getline(cin, yanma)) { getline(cin, ip1); getline(cin, ip2); string binaryip1, binaryip2, binaryyanma; if(youxiaoyanma(yanma, binaryyanma) && youxiaoip(ip1, binaryip1) && youxiaoip(ip2, binaryip2)) { if(yuyunsuan(binaryip1, binaryyanma) == yuyunsuan(binaryip2, binaryyanma)) { cout<<0<<endl; } else{ cout<<2<<endl; } } else{ cout<<1<<endl; } } } // 64 位输出请用 printf("%lld")