Java Program to Convert a Decimal Number to Binary Number using Arrays as Stacks
Last Updated :
11 Sep, 2022
Given an Integer number convert into Binary Number using arrays as a stack.
Example:
Input : 10
Output: 1010
Input : 16
Output: 10000
Approach:
- Divide the number by 2 and store the remainder of the number in the array.
- Divide the number by 2.
- Repeat the process until the number becomes zero.
- Print the array in reverse order.
Java
import java.util.*;
public class DecimalToBinary {
static int arr[] = new int [ 1000 ];
static int count;
public static void push( int n) {
arr[count++] = n;
}
public static void pop()
{
for ( int i = count - 1 ; i >= 0 ; i--) {
System.out.print(arr[i]);
}
}
public static void main(String args[])
{
int num = 46 ;
while (num > 0 ) {
int r = num % 2 ;
push(r);
num /= 2 ;
}
System.out.print( "Binary equivalent: " );
pop();
}
}
|
Output
Binary equivalent: 101110
Time complexity: O(logn) for given input number n
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...