admin管理员组

文章数量:1389829

I wanted to write a recursive function in js to calc the binary represenation of a decimal number.

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:

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.

How can I get rid of the leading 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.)

I wanted to write a recursive function in js to calc the binary represenation of a decimal number.

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./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.

How can I get rid of the leading 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.)

Share Improve this question edited Jan 18, 2013 at 12:40 VisioN 145k34 gold badges287 silver badges289 bronze badges asked Jan 18, 2013 at 12:03 Royi NamirRoyi Namir 149k144 gold badges493 silver badges831 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4

Here's a clean one I ported from 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. Whilst that parameter is false, you don't produce anything for a 0.

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

本文标签: recursionDecimal to binary recursive function in JavaScriptStack Overflow