题目描述
原理:ip地址的每段可以看成是一个0-255的整数,把每段拆分成一个二进制形式组合起来,然后把这个二进制数转变成一个长整数。
举例:一个ip地址为10.0.3.193
每段数字 相对应的二进制数
10 00001010
0 00000000
3 00000011
193 11000001
组合起来即为:00001010 00000000 00000011 11000001,转换为10进制数就是:167773121,即该IP地址转换后的数字就是它了。
数据范围:保证输入的是合法的 IP 序列
输入描述:
输入
1 输入IP地址
2 输入10进制型的IP地址
输出描述:
输出
1 输出转换成10进制的IP地址
2 输出转换后的IP地址
示例1
输入:10.0.3.193
167969729
输出:167773121
10.3.3.193
题解
下面展示本人题解思路代码。
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 (str = await readline()) {
if (str.split(".").length > 1) {
let arr = str.split(".");
str2 = []
for(item of arr) {
let bin = Number(item).toString(2)
bin = '0'.repeat(8-bin.length)+bin
str2.push(bin)
}
console.log(parseInt(str2.join(''),2));
} else {
let bin = Number(str).toString(2)
bin = '0'.repeat(32 - bin.length) + bin
const arr = []
for(let i = 0; i < 4; i++) {
const p = bin.slice(i*8, (i+1)*8)
arr.push(parseInt(p,2))
}
console.log(arr.join("."));
}
}
})();
文章系原创,在阅读过程中如若有误,劳请指正;如若有妙解、疑惑也欢迎大家和我交流,感谢!