How to Convert Decimal to Binary - Computing Fundamentals
2 and record the remainders; then read the remainders in reverse order to get the binary equivalent.Examples
How to Think About It
Algorithm
Code
def decimal_to_binary(n):
if n == 0:
return '0'
bits = []
while n > 0:
bits.append(str(n % 2))
n //= 2
bits.reverse()
return ''.join(bits)
print(decimal_to_binary(13))Dry Run
Let's trace converting decimal 13 to binary through the code
Initial number
n = 13, bits = []
Divide and record remainder
13 % 2 = 1, bits = ['1'], n = 13 // 2 = 6
Next division
6 % 2 = 0, bits = ['1', '0'], n = 6 // 2 = 3
Next division
3 % 2 = 1, bits = ['1', '0', '1'], n = 3 // 2 = 1
Next division
1 % 2 = 1, bits = ['1', '0', '1', '1'], n = 1 // 2 = 0
Reverse bits
bits reversed = ['1', '1', '0', '1']
| Iteration | n before division | Remainder | n after division | bits collected |
|---|---|---|---|---|
| 1 | 13 | 1 | 6 | ['1'] |
| 2 | 6 | 0 | 3 | ['1', '0'] |
| 3 | 3 | 1 | 1 | ['1', '0', '1'] |
| 4 | 1 | 1 | 0 | ['1', '0', '1', '1'] |
Why This Works
Step 1: Divide by 2 and find remainder
Each division by 2 splits the number into halves, and the remainder tells if the current bit is 0 or 1.
Step 2: Collect remainders
Remainders collected in order represent the binary digits but in reverse order.
Step 3: Reverse to get binary
Reversing the collected remainders gives the correct binary number from most significant bit to least.
Alternative Approaches
def decimal_to_binary_builtin(n):
return bin(n)[2:]
print(decimal_to_binary_builtin(13))def decimal_to_binary_recursive(n):
if n == 0:
return ''
return decimal_to_binary_recursive(n // 2) + str(n % 2)
print(decimal_to_binary_recursive(13) or '0')Complexity: O(log n) time, O(log n) space
Time Complexity
The number of divisions is proportional to the number of bits in the binary number, which is about log base 2 of n.
Space Complexity
We store each remainder bit, so space grows with the number of bits, also O(log n).
Which Approach is Fastest?
Using built-in functions is fastest and simplest, while manual division is educational and recursive methods are elegant but less efficient.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Manual division | O(log n) | O(log n) | Learning and understanding |
| Built-in function | O(1) | O(log n) | Quick conversion in real code |
| Recursive method | O(log n) | O(log n) | Elegant code, small inputs |