Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

将十进制数字转为二进制数字字符串 #114

Open
Sunny-117 opened this issue Nov 3, 2022 · 5 comments
Open

将十进制数字转为二进制数字字符串 #114

Sunny-117 opened this issue Nov 3, 2022 · 5 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@GlintonLiao
Copy link

使用内置方法

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
Copy link

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
Copy link
Contributor

veneno-o commented Mar 10, 2023

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
Copy link

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
Copy link

Windseek commented Apr 5, 2024

function transfrom (number) {
let rs = '';
let num = number;
while(num) {
let cur = num%2;
num = Math.floor(num/2);
rs = cur + '' + rs;
}
return rs;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants