Converting Binary To Octal number using HashMap in Java
Last Updated :
02 Nov, 2023
Remember while we were converting octal to decimal we were taking 3 binary digits at a time. A similar approach will be used where here for every 3 digits we are having a corresponding number as in octal system we have numbers from 0 to ‘R-1’ where R represents base value of number system. As the name suggests, in an octal number system, R is equivalent to 8. Hence, the number is as follows: 0,1,2,3,4,5,6,7.
Now going by virtue of HashMaps in converting one thing is clear from here that one way or other binary equivalent and octal equivalent are going to act as key-value pairs in our HashMap.
Illustration:
0 |
000 |
1 |
001 |
2 |
010 |
3 |
011 |
4 |
100 |
5 |
101 |
6 |
110 |
7 |
111 |
Algorithm:
- Convert the binary number into a decimal number.
- Using HashMap we map every bit with its decimal values.
- When the bit is found it maps with the decimal number
- Prints and display the octal equivalent of the number.
Example:
Input 1 : 1011
Output 1 : 13
Input 2 : 1000
Output 2 : 10
Implementation:
Java
import java.util.*;
public class GFG {
public static void octal(String s)
{
if (s.length() % 3 == 1 ) {
s = "00" + s;
}
else if (s.length() % 3 == 2 ) {
s = "0" + s;
}
HashMap<String, Integer> hm = new HashMap<>();
hm.put( "000" , 0 );
hm.put( "001" , 1 );
hm.put( "010" , 2 );
hm.put( "011" , 3 );
hm.put( "100" , 4 );
hm.put( "101" , 5 );
hm.put( "110" , 6 );
hm.put( "111" , 7 );
String[] part = new String[ 3 ];
int t = 0 ;
for ( int i = 0 ; i < s.length(); i = i + 3 ) {
String bypart = s.substring(i, i + 3 );
part[t] = bypart;
if (hm.containsKey(part[t])) {
System.out.print(hm.get(part[t]));
}
t++;
}
}
public static void main(String[] args)
{
System.out.print( "Enter the binary number to be converted : " );
String s = 011 ;
octal(s);
System.out.print( "Octal equivalent : " );
}
}
|
Output:
Enter the binary number to be converted : 011
Octal equivalent : 3
Time Complexity: O(N)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...