mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-12-19 07:00:35 +08:00
refactor: improving readability DecimalToAnyUsingStack (#6377)
refactor: improving readability DecimalToAnyUsingStack Co-authored-by: Deniz Altunkapan <93663085+DenizAltunkapan@users.noreply.github.com>
This commit is contained in:
committed by
GitHub
parent
95116dbee4
commit
7e37d94c53
@@ -2,17 +2,29 @@ package com.thealgorithms.stacks;
|
||||
|
||||
import java.util.Stack;
|
||||
|
||||
/**
|
||||
* Utility class for converting a non-negative decimal (base-10) integer
|
||||
* to its representation in another radix (base) between 2 and 16, inclusive.
|
||||
*
|
||||
* <p>This class uses a stack-based approach to reverse the digits obtained from
|
||||
* successive divisions by the target radix.
|
||||
*
|
||||
* <p>This class cannot be instantiated.</p>
|
||||
*/
|
||||
public final class DecimalToAnyUsingStack {
|
||||
|
||||
private DecimalToAnyUsingStack() {
|
||||
}
|
||||
|
||||
private static final char[] DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
|
||||
|
||||
/**
|
||||
* Convert a decimal number to another radix.
|
||||
*
|
||||
* @param number the number to be converted
|
||||
* @param radix the radix
|
||||
* @return the number represented in the new radix as a String
|
||||
* @throws IllegalArgumentException if <tt>number</tt> is negative or <tt>radix</tt> is not between 2 and 16 inclusive
|
||||
* @throws IllegalArgumentException if number is negative or radix is not between 2 and 16 inclusive
|
||||
*/
|
||||
public static String convert(int number, int radix) {
|
||||
if (number < 0) {
|
||||
@@ -26,18 +38,17 @@ public final class DecimalToAnyUsingStack {
|
||||
return "0";
|
||||
}
|
||||
|
||||
char[] tables = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
|
||||
|
||||
Stack<Character> bits = new Stack<>();
|
||||
Stack<Character> digitStack = new Stack<>();
|
||||
while (number > 0) {
|
||||
bits.push(tables[number % radix]);
|
||||
number = number / radix;
|
||||
digitStack.push(DIGITS[number % radix]);
|
||||
number /= radix;
|
||||
}
|
||||
|
||||
StringBuilder result = new StringBuilder();
|
||||
while (!bits.isEmpty()) {
|
||||
result.append(bits.pop());
|
||||
StringBuilder result = new StringBuilder(digitStack.size());
|
||||
while (!digitStack.isEmpty()) {
|
||||
result.append(digitStack.pop());
|
||||
}
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user