Write a program to convert a decimal number into an octal number.
Example 1:
Input:25
Output:31
Example 2:
Input:89
Output:131
Approach:
Java
public class DecimalToOctal {public static void main(String[] args) {int decimal = 89;String octal = decimalToOctal(decimal);System.out.println("Octal is " + octal);}public static String decimalToOctal(int decimal) {String octal = "";while (decimal > 0) {// calculate mode on base 8octal = decimal % 8 + "" + octal;decimal = decimal / 8;}return octal;}}
C++
#include <bits/stdc++.h>using namespace std;//Function to convert decimal to//octalstring decimalToOctal(int num){string octal="";while(num>0){octal+=to_string(num%8);num=num/8;}reverse(octal.begin(),octal.end());return octal;}int main(){int num=25;string octal=decimalToOctal(num);cout<<"Octal is ";cout<<octal<<"\n";return 0;}
No comments:
Post a Comment