题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
#include <cctype> #include <iostream> #include <string> #include <vector> #include <bitset> using namespace std; bool checkmask(string s){ bitset<32> b(s); int cout = b.count(); if(cout == 0 || cout == 32){ return false; } int a1 = s.find('0'), a2 = s.rfind('1'); if(a1 - a2 != 1){ return false; } return true; } vector<string> check(string s) { int n = s.size(), nums = 0, loc = 0; vector<string> res(1, "false"); // 默认 "false" string tmp, out; while (loc < n) { if (isdigit(s[loc])) { tmp += s[loc]; } else if (s[loc] == '.') { nums++; if (tmp.empty()) return res; // 空的分段无效 int val = stoi(tmp); if (val > 255) return res; // 超出范围 out += bitset<8>(val).to_string(); // 使用整数值转换 tmp.clear(); } else { return res; // 遇到非数字或非点字符 } loc++; } // 处理最后一个分段 if (!tmp.empty()) { int val = stoi(tmp); if (val > 255) return res; out += bitset<8>(val).to_string(); } else { return res; } // 检查分段数量是否正确 if (nums != 3) return res; // IPv4 应该有 3 个点,4 个分段 res[0] = "true"; res.push_back(out); return res; } int main() { string s; while(getline(cin,s)){ string s1,s2; getline(cin, s1); getline(cin, s2); vector<string> a,b,c; a = check(s); b = check(s1); c = check(s2); // 检查输入是否合法 if(a.size() == 1 || b.size() == 1 || c.size() == 1){ cout << "1" << endl; continue; } // 检查子网掩码是否合法 if(!checkmask(a[1])){ cout << "1" << endl; continue; } auto res1 = bitset<32>(a[1]) & bitset<32>(b[1]), res2 = bitset<32>(a[1]) & bitset<32>(c[1]); if(res1 == res2) { cout << "0" << endl; } else{ cout << "2" << endl; } } return 0; } // 64 位输出请用 printf("%lld")
bitset 真好用啊