Java Program to Convert Integer Values into Binary
Given an integer in Java, your task is to write a Java program to convert this given integer into a binary number.
Example:
Input: = 45
Output: = 101101
Input: = 32
Output: = 100000
Integers: Integers are numbers whose base value is 10. The Integer or int data type is a 32-bit signed two’s complement integer. Its value-range lies between – 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is – 2,147,483,648 and maximum value is 2,147,483,647. Its default value is 0. The int data type is generally used as a default data type for integral values unless there is no problem with memory.
Binary Numbers: A binary number is a number expressed in the base-2 numeral. Binary consists of only 2 digits 0 and 1. Two operators are used in the conversion of integers to binary modulo and division to convert the given input into binary numbers.
Approaches
There are many approaches to convert an integer into binary numbers some of them are discussed here. We will be discussing two of them:
- Using Implementation of Stack
- Using Inbuilt Method- toBinaryString() of the Integer class of Java
1. Using Implementation of Stack
Actually, the binary number consists of only 0 and 1. To convert an integer to binary divide the number by 2 until it becomes 0. In each step take the modulo by 2 and store the remainder into an array or stack. If we store the remainder into an array then print it into reverse order. If we store the remainder into a stack then simply pop one by one element and print it.
Below is the java implementation of the above approach:
Java
import java.io.*;
public class GFG {
static void printBinary( int [] binary, int id)
{
for ( int i = id - 1 ; i >= 0 ; i--)
System.out.print(binary[i] + "" );
}
public static void decimalToBinary( int num)
{
int [] binary = new int [ 35 ];
int id = 0 ;
while (num > 0 ) {
binary[id++] = num % 2 ;
num = num / 2 ;
}
printBinary(binary, id);
}
public static void main(String[] args)
{
int num = 45 ;
decimalToBinary(num);
}
}
|
Time Complexity: O(log2N)
Auxiliary Space: O(log2N)
Using Stack By Creating Object Vector
Java
import java.io.*;
import java.util.Stack;
public class GFG {
static void decimalToBinary( int num)
{
Stack<Integer> st = new Stack<>();
while (num > 0 ) {
st.push(num % 2 );
num = num / 2 ;
}
while (!(st.isEmpty())) {
System.out.print(st.pop());
}
}
public static void main(String[] args)
{
int num = 45 ;
decimalToBinary(num);
}
}
|
Time Complexity: O(log2N)
Auxiliary Space: O(log2N)
2. Using toBinaryString() inbuilt method of the Integer class of Java
Java
import java.io.*;
class GFG {
static void decimalToBinary( int num)
{
System.out.println(Integer.toBinaryString(num));
}
public static void main(String[] args)
{
int num = 45 ;
decimalToBinary(num);
}
}
|
Time Complexity: O(log2N)
Auxiliary Space: O(log2N)
Last Updated :
22 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...