题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
const rl = require("readline").createInterface({ input: process.stdin }); var iter = rl[Symbol.asyncIterator](); const readline = async () => (await iter.next()).value; void (async function () { // Write your code here while ((mask = await readline())) { let ip1 = await readline(); let ip2 = await readline(); console.log(Func(mask, ip1, ip2)); } function Func(mask, ip1, ip2) { let regIp = /^(\d{1,2}|1\d{2}|2[0-4][0-9]|25[0-5])\.(\d{1,2}|1\d{2}|2[0-4][0-9]|25[0-5])\.(\d{1,2}|1\d{2}|2[0-4][0-9]|25[0-5])\.(\d{1,2}|1\d{2}|2[0-4][0-9]|25[0-5])$/; let regMask = /^((255|254|252|248|240|224|192|128)\.0\.0\.0|255\.(255|254|252|248|240|224|192|128|0)\.0\.0|255\.255\.(255|254|252|248|240|224|192|128|0)\.0|255\.255\.255\.(254|252|248|240|224|192|128|0))$/; if(regMask.test(mask) && regIp.test(ip1) && regIp.test(ip2)){ let arrMask = ErJinZzhi(mask); let arrIp1 = ErJinZzhi(ip1); let arrIp2 = ErJinZzhi(ip2); let temp1=[], temp2=[]; for(let i=0; i<arrMask.length; i++){ temp1.push(arrMask[i] & arrIp1[i]); temp2.push(arrMask[i] & arrIp2[i]); } if(temp1.join('.') == temp2.join('.')){ return 0; }else{ return 2; } }else{ return 1; } } //将IP或掩码转换为10进制(便于后续做与运算) function ErJinZzhi(str){ let arr = str.split('.'); return arr.map(n => parseInt(n)); } })();