-
-
Notifications
You must be signed in to change notification settings - Fork 229
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
Comments
使用内置方法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" |
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)); 数学方法 |
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;
} |
function decimalToBinary(decimalNumber) {
let binary = '';
while(decimalNumber > 0) {
binary = (decimalNumber % 2) + binary;
decimalNumber = Math.floor(decimalNumber / 2);
}
return binary;
}
console.log(decimalToBinary(10)); // 输出 "1010" |
function transfrom (number) { |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: