1 整数与IP地址间的转换
function iptoNumber(ip){
let A=ip.split('.').map(v=>Number(v));
let num='';
for(let value of A){
let k=value.toString(2);//将每个数字转为二进制串
if(k.length<8){
for(let i=k.length;i<8;i++){
k='0'+k;
}//循环结束后得到长度为8的二进制串k
}
num+=k;
}
return parseInt(num,2);//将字符串num转为整数,数字的基数为2
}
function numbertoIp(number){
let str=Number(number).toString(2);
for(let j=str.length; j<32 ;j++){
str = '0' + str;
}
let first=parseInt(str.slice(0,8),2);
let second=parseInt(str.slice(8,16),2);
let third=parseInt(str.slice(16,24),2);
let forth=parseInt(str.slice(24,32),2);
return first+'.'+second+'.'+third+'.'+forth;
}
while(ip=readline(),num=readline()){
console.log(iptoNumber(ip));
console.log(numbertoIp(num));
}
2 蛇形矩阵
while(n = readline()) {
var num = Number(n);
var start = 1;//每行的初始值
for (let i = 1; i <=num; i++) {//行数
var flag = start;//flag记录每行的初始值
let tep = i + 1;
let str = start + ' ';
for (let j = num - i; j > 0; j--) {//列数
let next = start + tep;
str += next + ' ';
tep++;
start = next;
}//循环结束得到一行的值
start = flag + i;//每行的初始值
console.log(str);//这里自带换行
}
}