1

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

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

VisioN
  • 143,310
  • 32
  • 282
  • 281
Royi Namir
  • 144,742
  • 138
  • 468
  • 792

5 Answers5

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
2

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"
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • @RoyiNamir It can be even more elegant if we omit parenthesis `n % 2 + s` :) – VisioN Jan 18 '13 at 12:38
  • @RoyiNamir This is a [shortcut](http://stackoverflow.com/questions/5971645/what-is-the-double-tilde-operator-in-javascript) for `Math.floor`. – VisioN Jan 18 '13 at 13:20
2

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));
0

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.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
0
function binaryConversion(num) {
    if (num === 0) {
        return "";
    }
    return binaryConversion(Math.floor(num / 2)) + (num % 2).toString();
}