题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
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 let input = [] while(line = await readline()){ input.push(line) } //第一行 ip let ip = input[0] ipToInt(ip) //第二行 整数 let intip = input[1] intToIp(intip) }() const ipToInt=(input)=>{ //小数点分割 再把每一部分转为二进制 let ip = input.split('.') let binary = [] //注意要把二进制用0填充到8位 ip.forEach(item=>{ binary.push(Number(item).toString(2).padStart(8,0)) }) //最后把整个二进制串拼在一起输出十进制 console.log(parseInt(binary.join(''),2)) } const intToIp=(n)=>{ let binary = Number(n).toString(2).padStart(32,0) let res = '' while(binary.length>8){ res = '.'+parseInt(binary.slice(-8),2)+res // console.log(res) binary = binary.slice(0,binary.length-8) } res = parseInt(binary,2)+res console.log(res) }