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"
8 on 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
Step through toBinary(13) call by call