Advertisement
vencinachev

NumberSystems

Feb 18th, 2021
821
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.91 KB | None | 0 0
  1. import java.util.Stack;
  2.  
  3. public class Program {
  4.  
  5.     public static void decToBinString(int number) {
  6.         String bin = "";
  7.         while (number != 0) {
  8.             bin += number % 2;
  9.             number /= 2;
  10.         }
  11.         // reverse
  12.         for(int i = bin.length() - 1; i >= 0; i--) {
  13.             System.out.print(bin.charAt(i));
  14.         }
  15.     }
  16.    
  17.     public static void decToBinStack(int number) {
  18.         Stack<Integer> bin = new Stack<Integer>();
  19.         while (number != 0) {
  20.             bin.push(number % 2);
  21.             number /= 2;
  22.         }
  23.        
  24.         while (!bin.empty()) {
  25.             System.out.print(bin.pop());
  26.         }
  27.     }
  28.    
  29.     public static int binToDec(int bin) {
  30.         int dec = 0;
  31.         int power = 0;
  32.         while (bin != 0) {
  33.             dec += (bin % 10) * Math.pow(2, power);
  34.             power++;
  35.             bin /= 10;
  36.         }
  37.         return dec;
  38.     }
  39.    
  40.     public static void main(String[] args) {
  41.         while (true) {
  42.             System.out.println("1. BIN -> DEC");
  43.             System.out.println("2. DEC -> BIN");
  44.             System.out.println("3. EXIT");
  45.         }
  46.        
  47.     }
  48. }
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement