Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.lang.Math;;
- interface Stack<E> {
- E top();
- E pop();
- void push(E element);
- boolean isEmpty();
- }
- class ArrayStack<E> implements Stack<E> {
- public E arr[];
- private int t = -1;
- public int size() {
- return t + 1;
- }
- public ArrayStack(int capacity) {
- arr = (E[]) new Object[capacity];
- }
- public boolean isEmpty() {
- if (size() == 0) {
- return true;
- }
- return false;
- }
- public void push(E element) throws IllegalStateException {
- if (size() == arr.length) {
- throw new IllegalStateException("Stack is full");
- }
- // size++;
- arr[++t] = element;
- }
- public E pop() {
- if (isEmpty()) {
- return null;
- }
- E e = top();
- --t;
- return e;
- }
- public E top() {
- if (isEmpty()) {
- return null;
- }
- return arr[size() - 1];
- }
- }
- class dec_to_bin{
- ArrayStack<Long> a1=new ArrayStack<Long>(32);
- public void pushing(double num){
- while(num>=0){
- long x=(long)num % 2;
- a1.push(x);
- long y=(long)num/2;
- num=y;
- }
- }
- public void process(double num){
- double fracpart=num % 1; //This 2 lines will separate the integer part and fractional part of the number given
- long intpart=(long)num-(long)fracpart;
- if(fracpart==0){ //Checking if the given number is a floating point
- pushing(num); //This method will push the 1/0 onto the stack
- int len=a1.arr.length;
- for(int i=0;i<len;i++){ //This for loop will print the stack i.e. the binary number will get printed
- long e=a1.pop();
- System.out.print(e);
- }
- System.out.println();
- }
- else{
- pushing(intpart); //Since the number contains fractional part so I have implemented stack only for the integer part
- int a[]=new int[23];
- int i=0;
- while(i<23){
- fracpart=Math.round(fracpart*10000)/10000.0;
- double y=fracpart*2;
- int x=(int)y/10000;
- a[i++]=x;
- fracpart=y-x;
- if(fracpart==0)
- break;
- }
- int len=a1.arr.length;
- for(int j=0;j<len;j++){ //Loop= to print the integer part of binary number
- long e=a1.pop();
- System.out.print(e);
- }
- System.out.print(".");
- for(int k=0;k<a.length;k++){ //Loop= to print the fractional part of binary number
- System.out.print(a[k]);
- }
- System.out.println();
- }
- }
- }
- public class Main {
- public static void main(String args[]){
- Scanner sc=new Scanner(System.in);
- dec_to_bin d1 =new dec_to_bin();
- System.out.println("Enter decimal number");
- double nu=sc.nextDouble();
- d1.process(nu);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement