Thursday, 18 June 2020

Decimal To Binary Conversion Using Stack

Stack can be used to convert a number into it's binary form.
  1. Push the remainder into stack after dividing the number by 2.
  2. Keep doing 1, till number>0.
  3. Pop the binary remainders 1/0 to get the binary form.
 Following is the program:

package stacks;
import java.util.Iterator;
public class BinaryConvStack {
public String convert(int n) {
GenericStackResizeArrayItr<Integer> bitStack = new GenericStackResizeArrayItr<Integer>(5);
StringBuffer sb = new StringBuffer();
while(n>0) {
bitStack.push(n%2);
n=n/2;
}
Iterator<Integer> itr = bitStack.iterator();
while(itr.hasNext()) {
Integer i = bitStack.pop();
if(i==null)
break;
sb.append(i);
}
return sb.toString();
}
public static void main(String[] args) {
BinaryConvStack stack = new BinaryConvStack();
int i = 50;
System.out.println(i+" in binary is "+ stack.convert(i));
i=12345678;
System.out.println(i+" in binary is "+ stack.convert(i));
}
}
 

No comments:

Post a Comment