Editor

Binary by Stacking Remainders

#533 · Stacks and queues · Beginner · 30 XP · about 5 min

To write a number in binary, divide it by 2 again and again and note each remainder. The remainders come out last digit first, so push each one onto a stack and pop them to read the binary number in the right order.

Write to_binary(n) that returns the binary form of the whole number n as a string of '0' and '1' characters, with no leading zeros. The binary form of 0 is '0'.

Examples

to_binary(13)   # returns '1101'
to_binary(8)    # returns '1000'
to_binary(0)    # returns '0'

13 divided by 2 leaves remainders 1, 0, 1, 1 (and the number becomes 6, 3, 1, 0). Popped from the stack they read 1101.

Note

n is never negative.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.