题解 | #整数与IP地址间的转换#

整数与IP地址间的转换

https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let n = 0

rl.on('line', function (line) {
    n++
    if(n === 1){
        console.log(fn1(line))
    }else if(n === 2){
        console.log(fn2(line))
    }
});

// ip转成十进制
function fn1(ip){
    const arr = ip.split('.')
    let str = ''
    // 转成二进制拼起来的字符串
    str = arr.map(Number).reduce((s, cur)=>s += cur.toString(2).padStart(8, 0) , '')
    // 二进制转十进制
    return  parseInt(str, 2)
}

// 十进制转成ip
function fn2(num){
    // 转成二进制的字符串了
    const str = Number(num).toString(2).padStart(32,'0')
    // 每八位就转成一个十进制的数字
    const res = []
    for(let i = 0; i < 4; i++){
        res.push(parseInt(str.slice(i * 8, i * 8 + 8), 2))
    }

    return res.join('.')    
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
03-20 12:46
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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