Powers of Two
Base 2
Each bit is a coefficient on 1, 2, 4, 8…
Decimal-to-binary conversion turns a base-10 integer into a base-2 bit string. This tutorial covers remainders, bit scan, built-ins, a live preview, worked Python examples, edge cases, and complexity.
Base 2
Each bit is a coefficient on 1, 2, 4, 8…
n % 2
Collect bits LSB-first, then reverse for MSB-first output.
MSB → LSB
Read bits from the highest set position downward.
Special case
Return "0" — a plain while n > 0 loop would print nothing.
Try any n
Convert nonnegative integers instantly in the browser.
Complexity
Output length is about the bit length of n.
Decimal-to-binary conversion writes a nonnegative integer using only bits 0 and 1. Classic example: 15 = 8 + 4 + 2 + 1 → binary 1111.
The classroom method divides by 2 and stacks remainders (LSB first), then reverses. A bit-scan or format(n, "b") can produce the same string more directly.
It trains place value, loops, bit thinking, and the habit of handling zero and width rules in interviews.
First remainder is the rightmost bit.
MSB-first output needs a reverse (or bit scan).
Always return "0" for input 0.
bin / format after you know the theory.
In short: repeatedly take n % 2 and n //= 2, reverse the bits (or scan from the MSB), and special-case zero.
Given a nonnegative integer n, return its binary representation as a string (minimal bits, no leading zeros except for 0).
# 15 → remainders 1,1,1,1 → reverse → "1111"
# 8 → "1000"
# 0 → "0" | Item | Type | Description |
|---|---|---|
n | int | Nonnegative integer (define policy for negatives). |
| Return / print | str | Binary digits as a string, e.g. "1111". |
function decimal_to_binary(n):
if n == 0:
return "0"
bits = []
while n > 0:
bits.append(n % 2)
n = n // 2
reverse(bits)
return join(bits) | Method | Idea | Notes |
|---|---|---|
| Remainder + reverse | Collect n % 2, then reverse | Best classroom / interview explanation |
| Bit scan | MSB down to bit 0 with >> and & | No reverse step |
| Built-in | format(n, "b") / bin(n)[2:] | Idiomatic production Python |
| Goal | Pattern |
|---|---|
| Next bit | n % 2 |
| Shift right (divide) | n //= 2 |
| MSB-first output | bits.reverse() or scan high→low |
| Zero case | if n == 0: return "0" |
| Built-in | format(n, "b") |
| Padded width | format(n, "08b") |
Same binary string — different clarity and interview signaling.
% 2 + reverseShows place-value / division clearly
>> and &MSB-first without an explicit reverse
format / binShortest production style
remainders firstExplain loops, then mention built-ins
Reach for decimal-to-binary drills when base conversion and bits matter.
Checks loops, modulo, and LSB vs MSB understanding.
Makes powers of two concrete with 15 → 1111.
Same remainder idea extends to octal and hex.
Binary strings show up in flags, masks, and networking topics.
Fractional binaries need a different place-value story after the point.
Key benefit: one short problem that covers remainders, bit order, zero handling, and O(log n) reasoning.
Nonnegative integers in JavaScript safe range.
Three complete Python programs — remainder + reverse, bit scan, and built-in formatting. Click View Output to reveal sample console results.
Classic divide-by-two approach — collect, then reverse.
Collect remainder bits LSB-first, then reverse to print MSB-first.
def decimal_to_binary(n: int) -> str:
if n == 0:
return "0"
bits: list[str] = []
while n > 0:
bits.append(str(n % 2))
n //= 2
bits.reverse()
return "".join(bits)
print(decimal_to_binary(15)) # 1111
print(decimal_to_binary(0)) # 0 Remainders are collected from least significant bit to most significant bit, so reversing is required for normal left-to-right binary output.
Scan from the highest set bit downward — no reverse buffer.
Use bit_length() to find the top bit, then read each bit with shifts.
def to_binary_bit_scan(n: int) -> str:
if n == 0:
return "0"
highest = n.bit_length() - 1
out: list[str] = []
for b in range(highest, -1, -1):
bit = (n >> b) & 1
out.append("1" if bit else "0")
return "".join(out)
print(to_binary_bit_scan(15)) # 1111
print(to_binary_bit_scan(64)) # 1000000 bit_length() finds the highest bit position so you can scan MSB to LSB directly with (n >> b) & 1.
Same answer with built-ins — great after you know the algorithm.
format / binMinimal bits or fixed-width padding in one call.
def to_binary_builtin(n: int) -> str:
if n < 0:
raise ValueError("This helper expects a nonnegative integer")
return format(n, "b")
print(to_binary_builtin(15))
print(to_binary_builtin(0))
print(format(15, "08b")) # padded to 8 bits
print(bin(64)[2:]) # strip the '0b' prefix format(n, "b") is the cleanest minimal-bit conversion. Width specs like "08b" add leading zeros when a problem asks for fixed width.
If n == 0, return "0" immediately.
Append n % 2, then n //= 2 until n becomes 0.
Reverse the list (or have scanned MSB-first) and join into a string.
Return the MSB-first bit string — that is the base-2 form of n.
n = 15Trace the remainder method. Bits collect LSB-first, then reverse.
| n | n % 2 | n // 2 | bits so far |
|---|---|---|---|
15 | 1 | 7 | [1] |
7 | 1 | 3 | [1, 1] |
3 | 1 | 1 | [1, 1, 1] |
1 | 1 | 0 | [1, 1, 1, 1] |
Reverse → 1111. Check: 8 + 4 + 2 + 1 = 15.
Where decimal-to-binary conversion shows up beyond the interview prompt.
Tests remainder loops and bit-order fluency.
Example: write decimal_to_binary(n).
Makes 1, 2, 4, 8… concrete with 15 → 1111.
Example: chalkboard place values.
Bit strings help explain packed options.
Example: print permission bits.
Same remainder idea with base 8 or 16.
Example: next page — decimal to octal.
Pair with binary-to-decimal for inverse checks.
Example: assert int(bits, 2) == n.
Pad to 8/16/32 bits when a protocol requires it.
Example: format(n, "08b").
Pro Tip: say “first remainder is LSB” before coding — it prevents forgetting the reverse.
Why this pattern works well in interviews and classwork.
Remainders are exactly the binary digits.
format(n, "b") keeps application code short after the theory.
O(log n) steps and O(log n) output space are easy to argue.
Same method works for octal, hex, and custom bases.
Pro Tip: prepend bits with bits.insert(0, …) if you want to avoid an explicit reverse — still explain LSB order.
Small habits that keep decimal-to-binary solutions interview-ready.
Return "0" before the remainder loop.
Then reverse (or bit-scan) for MSB-first print.
Expect 1111 and 1000 as golden tests.
Ask whether minimal bits or padded width is required.
Show the loop first; then format(n, "b").
Pro Tip: round-trip with int(bits, 2) to catch reverse mistakes instantly.
Mistakes that commonly break decimal-to-binary solutions.
Printing remainders in collection order reverses the bits.
→ Reverse the list (or insert at front / bit-scan).
while n > 0 never runs when n is 0.
→ Return "0" explicitly.
Python // and % on negatives need a defined policy.
→ Reject or document abs / two’s complement.
Some graders expect padded 8-bit strings.
→ Ask whether minimal or fixed width is required.
bin(n) returns 0b... which often fails string checks.
→ Use bin(n)[2:] or format(n, "b").
Handle zero explicitly and define behavior for negatives before coding.
n == 0Return "0"; otherwise a plain while n > 0 loop returns empty output.
Choose absolute-value conversion or fixed-width two’s complement and document it.
Some tasks expect 00001111 instead of 1111.
One leading 1 and the rest zeros — good reverse checks.
n == 1Smallest positive case — return "1".
Practice the reverse conversion for interview completeness.
Handy follow-ups interviewers sometimes ask.
floor(log2 n) + 1 bits — that is n.bit_length() in Python.int(s, 2).Try these variations to lock in the pattern.
int(bits, 2)n == 0 separately.Quick Takeaway: collect n % 2 remainders, reverse them (or scan from the MSB), and special-case zero.
| Approach | Time | Extra space |
|---|---|---|
| Remainder + reverse | O(log n) | O(log n) |
| Bit scan using bit_length | O(log n) | O(log n) |
Built-in format(n, "b") | O(log n) | O(log n) (output) |
log is base 2 in bit-length terms for positive n.
Decimal-to-binary conversion is a clean remainder exercise: divide by 2, collect bits LSB-first, reverse for MSB-first output, and handle zero. Bit scan and format are strong follow-ups once the theory is clear.
Practice the three examples above, then continue to decimal-to-octal for the same pattern with base 8.
Always special-case 0, remember the first remainder is the LSB, and clarify minimal vs padded width.
Convert base 10 the interview-friendly way.
Remainders are bits
DefinitionLSB first
MathReturn "0"
GuardBit scan / format
CodeO(log n)
AnalysisRepeated division by 2 collects bits from least to most significant, so the usual classroom program prints the array backwards. A bit-scan loop can print from the MSB without an explicit reversal.
Learn how to convert decimal integers to octal with the same remainder pattern.
9 people found this page helpful