Decimal to Binary

Medium · rating 1050 · math

Read a non-negative integer n. Print its binary representation with no leading zeros (0 prints as 0).

Editorial

Decimal to Binary converts a non-negative integer to its base-2 representation — the inverse of binary-to-decimal.

Approach

Repeatedly divide by 2, collecting the remainders; those are the binary digits produced least-significant first, so reverse them at the end. Treat 0 as a special case.

if n == 0: return '0'
bits = []
while n:
    bits.append(str(n % 2))
    n //= 2
return ''.join(reversed(bits))

Complexity

Time: O(log n). Space: O(log n).

Open Decimal to Binary in Code Arena →