Decimal To Any Using Stack Algorithm

The Decimal To Any Using Stack Algorithm is a technique used to convert a given decimal number into any target base representation. This algorithm employs the use of a stack data structure to store the intermediate remainders during the conversion process. The stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle, making it a suitable choice for this conversion method. The algorithm is efficient and straightforward, enabling easy conversion of numbers between different bases, such as binary, octal, hexadecimal, or any other user-specified base. The algorithm starts by taking the input decimal number and target base as its parameters. It then initializes an empty stack and iteratively divides the decimal number by the target base, pushing the remainders onto the stack. After each division, the decimal number is updated to the quotient of the division. This process continues until the decimal number becomes zero. Once the decimal number is zero, the algorithm proceeds to pop the elements from the stack, which represent the digits of the converted number in the target base. These digits are then concatenated to form the final output in the desired base representation. The Decimal To Any Using Stack Algorithm is versatile and can easily be adapted to accommodate various base conversions by simply changing the target base parameter.
package DataStructures.Stacks;

import java.util.Stack;

public class DecimalToAnyUsingStack {
    public static void main(String[] args) {
        assert convert(0, 2).equals("0");
        assert convert(30, 2).equals("11110");
        assert convert(30, 8).equals("36");
        assert convert(30, 10).equals("30");
        assert convert(30, 16).equals("1E");
    }

    /**
     * Convert decimal number to another radix
     *
     * @param number the number to be converted
     * @param radix the radix
     * @return another radix
     * @throws ArithmeticException if <tt>number</tt> or <tt>radius</tt> is invalid
     */
    private static String convert(int number, int radix) {
        if (radix < 2 || radix > 16) {
            throw new ArithmeticException(
                    String.format("Invalid input -> number:%d,radius:%d", number, radix));
        }
        char[] tables = {
                '0', '1', '2', '3', '4',
                '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F'
        };
        Stack<Character> bits = new Stack<>();
        do {
            bits.push(tables[number % radix]);
            number = number / radix;
        } while (number != 0);

        StringBuilder result = new StringBuilder();
        while (!bits.isEmpty()) {
            result.append(bits.pop());
        }
        return result.toString();
    }
}

LANGUAGE:

DARK MODE: