Convert a non-negative integer to its binary string by repeated division by 2, without bin(). Understand why it takes O(log n) steps. Live tests.
The problem
Return the binary representation of the non-negative integer n as a string, without using bin() or format(). 0 → "0".
Examples
Example 1
Input
to_binary(10)
Expected output
'1010'
Example 2
Input
to_binary(1)
Expected output
'1'
+ 3 hidden tests on Submit.
Edge cases to ask about
- Zero
- Powers of two
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.
Pick both to reveal the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| Repeated division by 2 | O(log n) | O(log n) | Remainders give the bits from least significant up. |
Walkthrough of the optimal approach (try it yourself first)
Divide by 2 repeatedly and collect the remainders — they are the bits from least significant to most, so reverse them at the end. n halves each time, giving log₂(n) steps.
bin(n)[2:] and f"{n:b}" are the built-ins.
Complexity: O(log n) time, O(log n) space. n halves each step, so there are about log₂(n) steps and bits.
Reveal the reference solution
def to_binary(n): if n == 0: return "0" bits = [] while n: bits.append(str(n % 2)) n //= 2 return "".join(reversed(bits))
Follow-ups interviewers ask
- Convert binary back to decimal.
- Any base from 2 to 16.
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Convert Decimal to Binary in Python?
The optimal solution runs in O(log n) time and O(log n) auxiliary space. n halves each step, so there are about log₂(n) steps and bits.
What follow-up questions do interviewers ask about Convert Decimal to Binary?
Convert binary back to decimal. Any base from 2 to 16.
