Back to Practice Dashboard
Python BasicsEasy

Decimal to Octal Conversion

Learn how to solve the 'Decimal to Octal Conversion' problem. This detailed resource details brute force and optimized approaches.

Problem Statement

Easy

Write a function decimal_to_octal(n) that takes a non-negative integer n and returns a string representing its octal (base-8) equivalent. Do not include leading zeros (except for input 0, which should return '0').

To convert decimal to octal, repeatedly divide the number by 8 and collect the remainders in reverse order.

Constraints
  • 0 <= n <= 10^6

Examples

Example 1
Input
decimal_to_octal(100)
Output
'144'
Explanation

100 ÷ 8 = 12 remainder 4, 12 ÷ 8 = 1 remainder 4, 1 ÷ 8 = 0 remainder 1. Reading remainders bottom-up: 144.

Example 2
Input
decimal_to_octal(15)
Output
'17'
Explanation

15 ÷ 8 = 1 remainder 7, 1 ÷ 8 = 0 remainder 1. Result: 17.

Example 3
Input
decimal_to_octal(8)
Output
'10'
Explanation

8 ÷ 8 = 1 remainder 0, 1 ÷ 8 = 0 remainder 1. Result: 10.

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