Decimal to binary (recursion)
Easy TimeO(log n) SpaceO(log n)
Given a whole number n, zero or greater, return its binary form as a string: 13 is "1101". toString(2) and the like are off limits, and the digits come out most significant first.
Examples
Example 1
- Input
- n = 13
- Output
"1101"8 + 4 + 1 = 13, so the 8, 4 and 1 places are set and the 2 is not.
Example 2
- Input
- n = 8
- Output
"1000"8on its own, with the 4, 2 and 1 places empty behind it.
The Code
function toBinary(n) {
if (n === 0) return '';
return toBinary(Math.floor(n / 2)) + (n % 2);
}
toBinary(13);Done
More like this
All recursion examples (13) →- Fibonacci The classic branching recursion — every call spawns two more.
- Factorial The simplest linear recursion — one call, one multiply.
- Tower of Hanoi Move a stack of disks by trusting the recursion for the rest.
- GCD (Euclid) Euclid’s algorithm — recursion that shrinks fast.
- Power Raise a number to a power one multiply at a time.
- Sum of digits Peel one digit off at a time with the modulo trick.