22
33import java .util .Stack ;
44
5+ /**
6+ * Utility class for converting a non-negative decimal (base-10) integer
7+ * to its representation in another radix (base) between 2 and 16, inclusive.
8+ *
9+ * <p>This class uses a stack-based approach to reverse the digits obtained from
10+ * successive divisions by the target radix.
11+ *
12+ * <p>This class cannot be instantiated.</p>
13+ */
514public final class DecimalToAnyUsingStack {
15+
616 private DecimalToAnyUsingStack () {
717 }
818
19+ private static final char [] DIGITS = {'0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 'A' , 'B' , 'C' , 'D' , 'E' , 'F' };
20+
921 /**
1022 * Convert a decimal number to another radix.
1123 *
1224 * @param number the number to be converted
1325 * @param radix the radix
1426 * @return the number represented in the new radix as a String
15- * @throws IllegalArgumentException if <tt> number</tt> is negative or <tt> radix</tt> is not between 2 and 16 inclusive
27+ * @throws IllegalArgumentException if number is negative or radix is not between 2 and 16 inclusive
1628 */
1729 public static String convert (int number , int radix ) {
1830 if (number < 0 ) {
@@ -26,18 +38,17 @@ public static String convert(int number, int radix) {
2638 return "0" ;
2739 }
2840
29- char [] tables = {'0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 'A' , 'B' , 'C' , 'D' , 'E' , 'F' };
30-
31- Stack <Character > bits = new Stack <>();
41+ Stack <Character > digitStack = new Stack <>();
3242 while (number > 0 ) {
33- bits .push (tables [number % radix ]);
34- number = number / radix ;
43+ digitStack .push (DIGITS [number % radix ]);
44+ number /= radix ;
3545 }
3646
37- StringBuilder result = new StringBuilder ();
38- while (!bits .isEmpty ()) {
39- result .append (bits .pop ());
47+ StringBuilder result = new StringBuilder (digitStack . size () );
48+ while (!digitStack .isEmpty ()) {
49+ result .append (digitStack .pop ());
4050 }
51+
4152 return result .toString ();
4253 }
4354}
0 commit comments