题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.on('line', function (line) { if (line.includes('.')){ toTen(line) }else{ toIP(line) } }); function toIP(str:string){ const bistr = Number(str).toString(2).padStart(32,'0') const arr = [bistr.slice(0,8),bistr.slice(8,16),bistr.slice(16,24),bistr.slice(24,32)] const res = arr.map(_=>{ return parseInt(_,2) }) console.log(res.join('.')) } function toTen(ips:string){ const ip = ips.split('.') const arr = ip.map(_=>{ return +_ }).map(_=>{ return _.toString(2).padStart(8,'0') }) const str = arr.join('') console.log(parseInt(str, 2)) }
数字转n进制字符串 toString(n)
n进制字符串转十进制,parseInt(num, n)