@@ -6,50 +6,33 @@ public final class DecimalToAnyUsingStack {
6
6
private DecimalToAnyUsingStack () {
7
7
}
8
8
9
- public static void main (String [] args ) {
10
- assert convert (0 , 2 ).equals ("0" );
11
- assert convert (30 , 2 ).equals ("11110" );
12
- assert convert (30 , 8 ).equals ("36" );
13
- assert convert (30 , 10 ).equals ("30" );
14
- assert convert (30 , 16 ).equals ("1E" );
15
- }
16
-
17
9
/**
18
- * Convert decimal number to another radix
10
+ * Convert a decimal number to another radix.
19
11
*
20
12
* @param number the number to be converted
21
13
* @param radix the radix
22
- * @return another radix
23
- * @throws ArithmeticException if <tt>number</tt> or <tt>radius</tt> is
24
- * invalid
14
+ * @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
25
16
*/
26
- private static String convert (int number , int radix ) {
17
+ public static String convert (int number , int radix ) {
18
+ if (number < 0 ) {
19
+ throw new IllegalArgumentException ("Number must be non-negative." );
20
+ }
27
21
if (radix < 2 || radix > 16 ) {
28
- throw new ArithmeticException (String .format ("Invalid input -> number:%d,radius:%d" , number , radix ));
22
+ throw new IllegalArgumentException (String .format ("Invalid radix: %d. Radix must be between 2 and 16." , radix ));
23
+ }
24
+
25
+ if (number == 0 ) {
26
+ return "0" ;
29
27
}
30
- char [] tables = {
31
- '0' ,
32
- '1' ,
33
- '2' ,
34
- '3' ,
35
- '4' ,
36
- '5' ,
37
- '6' ,
38
- '7' ,
39
- '8' ,
40
- '9' ,
41
- 'A' ,
42
- 'B' ,
43
- 'C' ,
44
- 'D' ,
45
- 'E' ,
46
- 'F' ,
47
- };
28
+
29
+ char [] tables = {'0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 'A' , 'B' , 'C' , 'D' , 'E' , 'F' };
30
+
48
31
Stack <Character > bits = new Stack <>();
49
- do {
32
+ while ( number > 0 ) {
50
33
bits .push (tables [number % radix ]);
51
34
number = number / radix ;
52
- } while ( number != 0 );
35
+ }
53
36
54
37
StringBuilder result = new StringBuilder ();
55
38
while (!bits .isEmpty ()) {
0 commit comments