Decimal to Binary conversion
Learn how to solve the 'Decimal to Binary conversion' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
Write a function decimal_to_binary(n) that takes a non-negative integer n and returns a string representing its binary (base-2) equivalent. Do not include leading zeros (except for the input 0, which should return '0').
To convert decimal to binary, repeatedly divide the number by 2 and collect the remainders in reverse order.
- •0 <= n <= 10^6
Examples
decimal_to_binary(10)
'1010'
10 ÷ 2 = 5 remainder 0, 5 ÷ 2 = 2 remainder 1, 2 ÷ 2 = 1 remainder 0, 1 ÷ 2 = 0 remainder 1. Reading remainders bottom-up: 1010.
decimal_to_binary(255)
'11111111'
255 in binary is eight 1s: 128+64+32+16+8+4+2+1 = 255.
decimal_to_binary(0)
'0'
0 in any base is 0.
Need a Hint?
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.