Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save graphoarty/27beb3c1c8867687db465166109ee7cf to your computer and use it in GitHub Desktop.
Save graphoarty/27beb3c1c8867687db465166109ee7cf to your computer and use it in GitHub Desktop.
import java.util.Scanner;
public class DecimalToBinary {
static Scanner scan;
static int decValue;
static Stack stack;
public static void main(String[] args){
scan = new Scanner(System.in);
stack = new Stack();
System.out.println("Enter a number! ");
decValue = scan.nextInt();
while(decValue != 0){
stack.push(decValue%2);
decValue = decValue/2;
}
System.out.println("The binary value is! ");
while(!(stack.isStackEmpty())){
System.out.print(stack.pop());
}
}
}
public class Stack {
static final int max = 30;
int[] stack = new int[max];
int top;
Stack(){
top = 0;
}
int pop(){
try{
return stack[--top];
}catch(Exception e){
System.out.println("Cannot pop anymore!");
return -1;
}
}
void push(int num){
if(top<max){
stack[top++] = num;
}else{
System.out.println("Elements cannot be added!");
}
}
boolean isStackFull(){
if(top==max-1){
return true;
}else{
return false;
}
}
//Another function!
boolean isStackEmpty(){
if(top<=0){
return true;
}else{
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment