简体   繁体   English

JavaScript 中的十进制到二进制递归 function

[英]Decimal to binary recursive function in JavaScript

I wanted to write a recursive function in js to calc the binary represenation of a decimal number.我想在js中写一个递归的function来计算十进制数的二进制表示。

I did manage to solve this by:我确实设法通过以下方式解决了这个问题:

var t = (function f(n, s)
{
    return((s = (n % 2) + s) && (n == 0)) ? s : f(Math.floor(n / 2), s);
})(4, '');

console.log(t);

Fiddle: http://jsbin.com/ihezev/3/edit小提琴: http://jsbin.com/ihezev/3/edit

However, I can't get rid of the leading zero.但是,我无法摆脱前导零。

So if I execute the IIFE with 7 it yields: 0111 and I want 111 .因此,如果我用 7 执行 IIFE,它会产生: 0111并且我想要111

How can I get rid of the leading 0 ?我怎样才能摆脱领先的0

(without string replace solution please. I want to keep it as much elegant as I can.. and I know I can do alert(Number(234).toString(2)) but this question is tagged as recursion.) (请不要使用字符串替换解决方案。我想尽可能保持优雅。我知道我可以做alert(Number(234).toString(2))但这个问题被标记为递归。)

Here's a clean one I ported from python这是我从python移植的一个干净的

 const decToBi = num => num === 0 ? 0 : num % 2 + 10 * decToBi(Math.floor(num / 2)); console.log(decToBi(10)); //1010

A little bit changed but still elegant:有点变化但仍然优雅:

var t = (function f(n, s) {
    return n === 0 ? s || "0" : f(~~(n / 2), (n % 2) + s);
})(7, "");  // "111"

 function base10ToString(num, str = "") { if (num === 0) { return str; } if (num % 2 === 0) str = "0" + str; else str = "1" + str; return base10ToString(Math.floor(num / 2), str); } console.log(base10ToString(7));

You'll need to pass a parameter which represents whether you've produced a 1 yet.您需要传递一个参数来表示您是否已经生成了1 Whilst that parameter is false , you don't produce anything for a 0 .虽然该参数为false ,但您不会为0生成任何内容。

function binaryConversion(num) {
    if (num === 0) {
        return "";
    }
    return binaryConversion(Math.floor(num / 2)) + (num % 2).toString();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM