C++ Program For Octal To Decimal Conversion
Last Updated :
03 Jul, 2023
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: 55
Input : 512
Output: 330
Input : 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++
#include <iostream>
using namespace std;
int octalToDecimal( int n)
{
int num = n;
int dec_value = 0;
int base = 1;
int temp = num;
while (temp)
{
int last_digit = temp % 10;
temp = temp / 10;
dec_value += last_digit * base;
base = base * 8;
}
return dec_value;
}
int main()
{
int num = 67;
cout << octalToDecimal(num) << endl;
}
|
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++
#include <iostream>
using namespace std;
int OctToDec(string n)
{
return stoi(n, 0, 8);
}
int main()
{
string n = "67" ;
cout << OctToDec(n);
return 0;
}
|
Please refer complete article on Program for Octal to Decimal Conversion for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...