Back to Practice Dashboard
Python BasicsEasy

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

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?
Use simple arithmetic operators (like modulo `%`, division `//`), conditional checks, or loops to inspect number properties.
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.

Open in Editor