Skip to the content

The lighthouse in binary

Problem

When fog rolls in, the Grey Point lighthouse talks to ships in flashes: a long one is a 1 and a short one is a 0. That way it sends numbers in binary, and the keeper asks you to get each message ready.

Write a function that takes a whole number, 0 or greater, and returns it written in binary as a string of zeros and ones. It is a string, not a number: for 13 you return "1101", not the number 1101.

You get it by dividing by 2 until you reach 0, and each remainder is a digit: 13 divided by 2 is 6, remainder 1; 6 by 2 is 3, remainder 0; 3 by 2 is 1, remainder 1; 1 by 2 is 0, remainder 1. Read the remainders from last to first and you get 1101.

No leading zeros, and 0 is written "0".

Examples

  • The example

    13 → "1101"

  • One

    1 → "1"

  • Ends in zero

    6 → "110"

  • Eight ones

    255 → "11111111"

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def to_binary(n):
    pass

JavaScript

function toBinary(n) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. It is free and you do not need an account to start.

More O(log n) challenges

See all challenges →