Python Program to Find Binary Equivalent of Number
bin(number) to get the binary equivalent of a number as a string prefixed with '0b', or use format(number, 'b') to get it without the prefix.Examples
How to Think About It
Algorithm
Code
def decimal_to_binary(num): if num == 0: return '0' binary = '' while num > 0: binary = str(num % 2) + binary num //= 2 return binary number = int(input('Enter a number: ')) print('Binary equivalent:', decimal_to_binary(number))
Dry Run
Let's trace the input 5 through the code
Start with number 5
num = 5, binary = ''
Calculate remainder and update binary
5 % 2 = 1, binary = '1', num = 5 // 2 = 2
Next iteration
2 % 2 = 0, binary = '0' + '1' = '01', num = 2 // 2 = 1
Next iteration
1 % 2 = 1, binary = '1' + '01' = '101', num = 1 // 2 = 0
Loop ends, return binary
binary = '101'
| num | num % 2 | binary | num // 2 |
|---|---|---|---|
| 5 | 1 | 1 | 2 |
| 2 | 0 | 01 | 1 |
| 1 | 1 | 101 | 0 |
Why This Works
Step 1: Check for zero
If the input number is zero, return '0' immediately because its binary is simply 0.
Step 2: Divide and find remainder
Divide the number by 2 and find the remainder; this remainder is the least significant bit of the binary number.
Step 3: Build binary string
Prepend each remainder to the binary string to build the binary number from least to most significant bit.
Alternative Approaches
number = int(input('Enter a number: ')) binary = bin(number)[2:] print('Binary equivalent:', binary)
number = int(input('Enter a number: ')) binary = format(number, 'b') print('Binary equivalent:', binary)
Complexity: O(log n) time, O(log n) space
Time Complexity
The time depends on the number of bits in the number, which is proportional to log base 2 of the number.
Space Complexity
The space needed is proportional to the number of bits to store the binary string.
Which Approach is Fastest?
Using built-in functions like bin() or format() is fastest and simplest compared to manual division.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Manual division | O(log n) | O(log n) | Learning binary conversion logic |
| bin() function | O(log n) | O(log n) | Quick and easy conversion |
| format() function | O(log n) | O(log n) | Clean binary string without prefix |
bin(number)[2:] or format(number, 'b') for quick binary conversion in Python.bin() and get unexpected output.