C++ Program For Octal To Decimal Conversion
Last Updated :
03 Jul, 2023
Improve
Given an octal number as input, we need to write a program to convert the given octal number into an equivalent decimal number.
Examples:
Input : 67
Output: 55Input : 512
Output: 330Input : 123
Output: 83
1. Simple Approach
- The idea is to extract the digits of a given octal number starting from the rightmost digit and keep a variable dec_value.
- At the time of extracting digits from the octal number, multiply the digit with the proper base (Power of 8) and add it to the variable dec_value.
- In the end, the variable dec_value will store the required decimal number.
Example:
If the octal number is 67.
dec_value = 6*(8^1) + 7*(8^0) = 55
The below diagram explains how to convert an octal number (123) to an equivalent decimal value:
Below is the implementation of the above idea.
// C++ program to convert octal
// to decimal
#include <iostream>
using namespace std;
// Function to convert octal
// to decimal
int octalToDecimal(int n)
{
int num = n;
int dec_value = 0;
// Initializing base value to 1,
// i.e 8^0
int base = 1;
int temp = num;
while (temp)
{
// Extracting last digit
int last_digit = temp % 10;
temp = temp / 10;
// Multiplying last digit with
// appropriate base value and adding
// it to dec_value
dec_value += last_digit * base;
base = base * 8;
}
return dec_value;
}
// Driver code
int main()
{
int num = 67;
cout << octalToDecimal(num) << endl;
}
Output
55
The complexity of the above method
Time complexity: O(logN) where N is the given number
Auxiliary space: O(1)
2. Using Predefined stoi() Function
Below is the C++ program for Octal to Decimal Conversion:
// C++ program to convert octal
// to decimal
#include <iostream>
using namespace std;
int OctToDec(string n)
{
return stoi(n, 0, 8);
}
// Driver code
int main()
{
string n = "67";
cout << OctToDec(n);
return 0;
}
// This code is contributed by phasing17
Output
55
Please refer complete article on Program for Octal to Decimal Conversion for more details!