Editor

Binary by Recursion

#581 · Recursion and backtracking · Intermediate · Find and fix · 60 XP · about 8 min

to_binary(n) should return the binary digits of a whole number n as a string, with no leading zeros, and it does so with recursion: the function calls itself on a smaller number. to_binary(6) is '110', because 6 is 4 + 2, and to_binary(0) is '0'.

The code in the editor has two bugs. Numbers such as 5 and 7 come out right, but to_binary(6) gives '011', and to_binary(0) gives an empty string.

Examples

to_binary(5)   # returns '101'
to_binary(6)   # returns '110'
to_binary(1)   # returns '1'
to_binary(0)   # returns '0'

Constraints

  • 0 <= n <= 10**9

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.