题解 | #整数与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;
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
11-29 12:19
点赞 评论 收藏
分享
11-07 13:31
怀化学院 Java
勇敢牛牛不怕难:又疯一个
点赞 评论 收藏
分享
10-30 22:18
已编辑
毛坦厂中学 C++
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务