题解 | #整数与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(".")) {
            const arr = line.split(".");
            const towArray = [];
            arr.forEach((item) => {
                let num = parseInt(item);
                let string = num.toString(2);
                let len = string.length;
                for (let i = 0; i < 8 - len; i++) {
                    string = "0" + string;
                }
                towArray.push(string);
            });
            console.log(twoToTen(towArray));
        } else {
           console.log(tenToTwo(line).join("."));
        }
    }
})();

function twoToTen(arr) {
    const string = arr.join("");
    let res = 0;
    for(let i = string.length - 1; i >= 0; i--) {
        res += parseInt(string[i]) * Math.pow(2, string.length - i - 1);
    }
    return res;
}

function tenToTwo(num) {
    let tmp = parseInt(num);
    let res = tmp.toString(2);
    let result = [];
    while (res.length < 32) {
        res = '0' + res;
    }
    let a = res.slice(0, 8), b = res.slice(8, 16), c = res.slice(16, 24), d = res.slice(24);
    result.push(help(a));
    result.push(help(b));
    result.push(help(c));
    result.push(help(d));
    return result;
}

function help(num) {
    let res = 0;
    for(let i = num.length - 1; i >= 0; i--) {
        res += parseInt(num[i]) * Math.pow(2, num.length - i - 1);
    }
    return res;
}

全部评论

相关推荐

只写bug的程序媛:人家说一本以上,不是及以上
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务