Python Program to Convert Decimal to Binary
bin(number)[2:] or by writing a function that divides the number by 2 repeatedly and collects remainders.Examples
How to Think About It
bin() function can be used and the first two characters removed.Algorithm
Code
def decimal_to_binary(n): if n == 0: return '0' binary = '' while n > 0: binary = str(n % 2) + binary n = n // 2 return binary number = 10 print(decimal_to_binary(number))
Dry Run
Let's trace the decimal number 10 through the code.
Initial number
n = 10, binary = ''
First division
10 % 2 = 0, binary = '0', n = 10 // 2 = 5
Second division
5 % 2 = 1, binary = '1' + '0' = '10', n = 5 // 2 = 2
Third division
2 % 2 = 0, binary = '0' + '10' = '010', n = 2 // 2 = 1
Fourth division
1 % 2 = 1, binary = '1' + '010' = '1010', n = 1 // 2 = 0
End loop
n = 0, stop loop, return '1010'
| n before division | Remainder (n % 2) | binary string | n after division (n // 2) |
|---|---|---|---|
| 10 | 0 | 0 | 5 |
| 5 | 1 | 10 | 2 |
| 2 | 0 | 010 | 1 |
| 1 | 1 | 1010 | 0 |
Why This Works
Step 1: Divide and get remainder
Each division by 2 gives a remainder of 0 or 1, which is a binary digit.
Step 2: Build binary string backwards
We add each remainder to the front of the string because the first remainder is the least significant bit.
Step 3: Stop when number is zero
When the number becomes zero, all binary digits are collected and the loop ends.
Alternative Approaches
number = 10 binary = bin(number)[2:] print(binary)
def decimal_to_binary_recursive(n): if n == 0: return '' return decimal_to_binary_recursive(n // 2) + str(n % 2) number = 10 binary = decimal_to_binary_recursive(number) or '0' print(binary)
Complexity: O(log n) time, O(log n) space
Time Complexity
The loop runs once for each binary digit, which is proportional to log base 2 of the number.
Space Complexity
The binary string stores one character per binary digit, so space grows with log base 2 of the number.
Which Approach is Fastest?
Using Python's built-in bin() is fastest and simplest; manual methods are educational but slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Manual division loop | O(log n) | O(log n) | Learning and understanding binary conversion |
| Built-in bin() function | O(1) practically | O(log n) | Quick and efficient conversion |
| Recursive method | O(log n) | O(log n) | Understanding recursion, less efficient for large inputs |
bin(number)[2:] for a quick decimal to binary conversion in Python.