题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
利用 >>> 和 &1 拿到各个位数的数字,效率比直接调用api会好些
let line let arr = [] let decimalismIP; while(line = readline()) { if(line.split('.').length > 2) { const agencyArr = line.split('.') agencyArr.forEach(item => { arr.push(parseInt(item)) }) }else { decimalismIP = parseInt(line) } } // console.log(arr) let binaryArr = [] arr.forEach(item => { const temp = new Array(8) for(let i=0; i<8; i++) { temp[7 - i] = item & 1 item >>>= 1 } binaryArr.push(...temp) }) const res = parseInt(binaryArr.join(''), 2) print(res) let decimalismToIp = new Array(32) for(let i=0; i<32; i++) { decimalismToIp[31 - i] = decimalismIP & 1; decimalismIP >>>= 1; } let secondArr = [] let num = 0; let tempStr = '' for(let i=0; i<decimalismToIp.length; i++) { tempStr += decimalismToIp[i] num++ if(num == 8) { num = 0 secondArr.push(parseInt(tempStr, 2)) tempStr = '' } } print(secondArr.join('.'))