Python BasicsEasy

Decimal to Binary conversion

Detailed guide and Python implementation for the 'Decimal to Binary conversion' problem.

Problem Statement

Easy

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.

Constraints
  • 0 <= n <= 10^6

Examples

Example 1
Input
decimal_to_binary(10)
Output
'1010'
Explanation

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.

Example 2
Input
decimal_to_binary(255)
Output
'11111111'
Explanation

255 in binary is eight 1s: 128+64+32+16+8+4+2+1 = 255.

Example 3
Input
decimal_to_binary(0)
Output
'0'
Explanation

0 in any base is 0.

Need a Hint?
Consider using Numbers-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.