题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); const getMulti = (n: number) => { let result = 1; while (n) { n -= 1; result *= 2; } return result; }; rl.on("line", function (line) { const tokens = line.split(" "); const raw = tokens[0]; const isIp = raw.includes("."); const result = isIp ? ipToDecimal(raw) : decimalToIP(raw); console.log(result); }); const ipToDecimal = (raw: string) => { const list = raw .split(".") .map((v: string) => parseInt(v)) .reverse(); let sum = 0; for (let i = 0, count = list.length; i < count; i++) { const cur = list[i]; const multiple = getMulti(i * 8); sum += cur * multiple; } return sum; }; const decimalToIP = (raw: string) => { let list = []; let remainder = parseInt(raw); for (let step = 3; step >= 0; step--) { const multi = getMulti(step * 8); const quotient = Math.floor(remainder / multi); remainder = Math.floor(remainder % multi); list.push(quotient); } const result = list.join("."); return result; };