Open In App

Octal to Decimal conversion using JavaScript

Last Updated : 08 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

An octal number is a number system that uses a base of 8 and numbers are represented using the digits 0 through 7. Decimal numbers are a base 10 number system which uses 10 digits from 0 to 9. We are given a number a octal number and we have to convert it into decimal in JavaScript and print the result.

Example:

Input: '17'
Output: 15

There are several approaches to converting an Octal number to a decimal number using JavaScript which are as follows:

Using parseInt() Function

In this approach, there is an inbuilt function parseInt which will convert the octal number into its decimal equivalent. Use the ‘parseInt’ function with base 8 to convert octal to decimal to convert the octal string to its decimal equivalent.

Example: Demonstration of converting of octal to decimal using the inbuilt parseInt().

JavaScript
function octalToDecimal(octal) {
    return parseInt(octal, 8);
}

console.log(octalToDecimal('17')); 

Output
15

Time Complexity: O(n).

Space Complexity: O(1).

Using Iteration

Create a function and initialize two variables decimal to store answer and power to keep track of the position’s power of 8. Start a loop from the last digit of the octal string to the first. For each digit, convert it to a decimal using parseInt() and multiply it by 8 raised to the power of its position. Then, add this value to the decimal variable. After loop completes return decimal.

Example: Demonstration of converting of octal to decimal by manual conversion.

JavaScript
function octalToDecimal(octal) {
    let decimal = 0;
    let power = 0;
    for (let i = octal.length - 1; i >= 0; i--) {
        decimal += parseInt(octal[i]) * Math.
            pow(8, power);
        power++;
    }
    return decimal;
}

console.log(octalToDecimal('17'));

Output
15

Time Complexity: O(n).

Space Complexity: O(1).

Functional Approach

We will create a function. Then we Split the octal string into an array of digits. now we reverse the array of digits. Use reduce() method to iterate over the reversed array of digits. For each digit, calculate its decimal value by multiplying it by 8 raised to the power of its index. Accumulate the decimal values using the reduce() method. After the reduce() operation is complete, return accumulated decimal value.

Example: Demonstration of converting of octal to decimal by using functional approach.

JavaScript
function octalToDecimal(octal) {
    return octal
        .split('')
        .reverse()
        .reduce((acc, digit, index) => {
            return acc + digit * Math
                .pow(8, index);
        }, 0);
}

console.log(octalToDecimal('17'));

Output
15

Time complexity: O(n)

Space complexity: O(n)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads