Advertisement
joxaren

BinaryToDecimalConverter

Apr 10th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.05 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.LinkedList;
  3.  
  4. public class BinaryToDecimalConverter { // only works with small int numbers cuz i'm lazy
  5.  
  6.     private static int convertBinaryToDecimal(int number) {
  7.         ArrayList<Integer> list = new ArrayList<>(); // a list of separate digits of the number being converted
  8.         LinkedList<Integer> stack = new LinkedList<>(); // a stack used to put the digits onto the list in the right order after separating them
  9.  
  10.         while (number > 0) { // get separate digits of the number, put them on a stack
  11.             stack.push(number % 10);
  12.             number = number / 10;
  13.         }
  14.  
  15.         while (!stack.isEmpty()) { // put digits onto the list in correct order
  16.             list.add(stack.pop());
  17.         }
  18.  
  19.         int decimalNumber = 0;
  20.         int digits = list.size() - 1;
  21.         for (int item : list) { // converts into decimal using base-q expansion representation of the number
  22.             decimalNumber += item << digits;
  23.             digits--;
  24.         }
  25.         return decimalNumber;
  26.     }
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement