Write a program to convert the binary number to an octal number.
Example 1:
Input:1101
Output:15
Example 2:
Input:11010
Output:32
Approach: Make groups of 3 and find the decimal value of each group
Java
public class BinaryToOctal {public static void main(String[] args) {String binary = "11010";String octal = binaryToOctal(binary);System.out.println("Octal is " + octal);}public static String binaryToOctal(String binary) {String octal = "";// check binary length divisible by 3int l = binary.length() % 3;// add remaining 0 in prefixif (l != 0) {l = 3 - l;while (l > 0) {binary = "0" + binary;l--;}}// loop run in 3-3 groupfor (int i = binary.length() - 1; i >= 0; i = i - 3) {int sum = 0;int power = 0;for (int j = i; j > i - 3; j--) {if (binary.charAt(j) == '1') {sum += Math.pow(2, power);}power++;}octal = sum + "" + octal;}return octal;}}
C++
#include <bits/stdc++.h>using namespace std;//Function to convert binary//to octalstring binaryToOctal(string s){int n=s.size();int m=n%3;if(m!=0)m=3-m;reverse(s.begin(),s.end());while(m--)s+='0';//new length of stringn=s.size();string ans="";reverse(s.begin(),s.end());for(int i=0;i<=n-3;i+=3){int res=0;for(int j=0;j<3;j++){if(s[i+j]=='1')res=res+pow(2,2-j);}ans+=to_string(res);}return ans;}int main(){string str="1101";string octal=binaryToOctal(str);cout<<"Octal is ";cout<<octal<<"\n";return 0;}//Time Complexity: O(n)//Space Complexity:O(1)
No comments:
Post a Comment