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