将十进制数字转为二进制数字字符串
Sunny-117 opened this issue · 5 comments
Sunny-117 commented
将十进制数字转为二进制数字字符串
GlintonLiao commented
使用内置方法
const x = 10
console.log(x.toString(2)) // "1010"
手动实现
let x = 10
let str = ''
while (x) {
str += x & 1 ? '1' : '0'
x >>= 1
}
console.log(str.split('').reverse().join('')) // "1010"
bearki99 commented
function transform(num){
let res = '';
while(num){
let val = num % 2;
num = Math.floor(num / 2);
res = val + res;
}
return res;
}
console.log(transform(10));
数学方法
veneno-o commented
function transform(num){
if(num === 0) return "0";
let res = "";
while(!(Object.is(num, +0) || Object.is(num, -0))){
res = ((num & 1) === 1 ? "1" : "0") + res;
num >>= 1;
}
return res;
}
kangkang123269 commented
function decimalToBinary(decimalNumber) {
let binary = '';
while(decimalNumber > 0) {
binary = (decimalNumber % 2) + binary;
decimalNumber = Math.floor(decimalNumber / 2);
}
return binary;
}
console.log(decimalToBinary(10)); // 输出 "1010"
Windseek commented
function transfrom (number) {
let rs = '';
let num = number;
while(num) {
let cur = num%2;
num = Math.floor(num/2);
rs = cur + '' + rs;
}
return rs;
}