题解 | #整数与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
    while (line = await readline()) {
        if (line.includes('.')) {
            toNum(line);
        } else {
            toIp(line);
        }
    }

    function toIp(num) {
        const res = parseInt(num).toString(2).padStart(32,'0');
        let arr = [res.slice(0,8),res.slice(8,16),res.slice(16,24),res.slice(24,32)];
        console.log(arr.map(item=>parseInt(item,2)).join('.'));
    }

    function toNum(ip) {
        let result = [];
        const arr = ip.split('.');
        for (let i = 0; i < arr.length; i++) {
            const res1 = parseInt(arr[i]).toString(2);
            const res2 = res1.padStart(8, '0');
            result.push(res2);
        }
        let toTen = '';
        for (let i = 0; i < result.length; i++) {
            toTen += result[i];
        }
        console.log(parseInt(toTen, 2));
    }
}()

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务