easy
1 views

Octal Equivalent Of N

Convert a decimal integer to its octal representation

Understand the Problem

Problem Statement

Given an integer N as input, the program must print the octal equivalent of N.

Constraints

  • 1 <= N <= 10000000

Examples

Example 1
Input
4756
Output
11224
Explanation

The octal equivalent of 4756 is 11224. This is calculated by repeatedly dividing 4756 by 8: 4756 ÷ 8 = 594 remainder 4, 594 ÷ 8 = 74 remainder 2, 74 ÷ 8 = 9 remainder 2, 9 ÷ 8 = 1 remainder 1, 1 ÷ 8 = 0 remainder 1. Reading remainders from bottom to top gives 11224.

Example 2
Input
49467
Output
140473
Explanation

The octal equivalent of 49467 is 140473. This is calculated by repeatedly dividing 49467 by 8: 49467 ÷ 8 = 6183 remainder 3, 6183 ÷ 8 = 772 remainder 7, 772 ÷ 8 = 96 remainder 4, 96 ÷ 8 = 12 remainder 0, 12 ÷ 8 = 1 remainder 4, 1 ÷ 8 = 0 remainder 1. Reading remainders from bottom to top gives 140473.

Solution

#include <stdio.h>

int main() {
    int decimal, octal = 0, i = 1, remainder;
    
    scanf("%d", &decimal);
    
    while (decimal != 0) {
        remainder = decimal % 8;
        octal = octal + remainder * i;
        decimal = decimal / 8;
        i = i * 10;
    }
    
    printf("%d", octal);
    return 0;
}
Time:O(log n) where n is the input number
Space:O(1)
Approach:

The C solution reads the decimal number, then enters a loop where it repeatedly divides by 8. The remainder of each division (decimal % 8) gives the next octal digit. This digit is multiplied by the appropriate power of 10 (i) and added to the result. The loop continues until the decimal number becomes 0.

Visual Explanation

Loading diagram...