题解 | #二进制转换#
二进制转换
http://www.nowcoder.com/practice/7b74386695cc48349af37196f45e62a8
二进制转换
给定数字除2,将余数保存到栈中(用数组模拟),最后将数组反转输出为字符串。
// 创建长度为8的数组
let result = [];
let rem;
while (num > 0) {
rem = Math.floor(num % 2);
result.push(rem)
num = Math.floor(num / 2);
}
// 不足8位补齐
for(let i=0; i<8; i++){
if(result[i]==undefined) {
result[i] = 0;
}
}
// 反转输出
return result.reverse().join('');