Write a program to convert an octal number into a binary number.
Example 1:
Input:324
Output:011010100
Example 2:
Input:62
Output:110010
Approach
Java
public class OctalToBinary {public static void main(String[] args) {int octal = 324;String binary = octalToBinary(octal);System.out.println("Binary is " + binary);}public static String octalToBinary(int octal) {String binary = "";while (octal > 0) {int mod = octal % 10;if (mod == 0) {binary = "000" + binary;} else {binary = decimalToBinary(mod) + binary;}octal = octal / 10;}return binary;}public static String decimalToBinary(int decimal) {String binary = "";while (decimal > 0) {// if decimal%2==0 then append 0 else append 1if (decimal % 2 == 0) {binary = "0" + binary;} else {binary = "1" + binary;}decimal = decimal / 2;}// if length is <3 the append '0' in binary prefixwhile (binary.length() < 3) {binary = '0' + binary;}return binary;}}
C++
#include <bits/stdc++.h>using namespace std;string decimalToBinary(int n){//varibale to store the final//resultstring res="";while(n>0){//if n%2==0 then appen 0if(n%2==0)res+='0';//if n%2==1 then appen 1elseres+='1';n=n/2;}while(res.size()<3){res+='0';}//reverse the resultreverse(res.begin(),res.end());return res;}//Function to convert from octal//to binarystring octalToBinary(int octal){string binary="";while(octal>0){int mod=octal%10;if(mod==0)binary="000"+binary;elsebinary= decimalToBinary(mod)+binary;octal=octal/10;}return binary;}int main(){int octal=324;string binary=octalToBinary(octal);cout<<"Binary is ";cout<<binary<<"\n";return 0;}
No comments:
Post a Comment