- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathDecimalToAnyUsingStack.java
43 lines (36 loc) · 1.32 KB
/
DecimalToAnyUsingStack.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
packagecom.thealgorithms.stacks;
importjava.util.Stack;
publicfinalclassDecimalToAnyUsingStack {
privateDecimalToAnyUsingStack() {
}
/**
* 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
*/
publicstaticStringconvert(intnumber, intradix) {
if (number < 0) {
thrownewIllegalArgumentException("Number must be non-negative.");
}
if (radix < 2 || radix > 16) {
thrownewIllegalArgumentException(String.format("Invalid radix: %d. Radix must be between 2 and 16.", radix));
}
if (number == 0) {
return"0";
}
char[] tables = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
Stack<Character> bits = newStack<>();
while (number > 0) {
bits.push(tables[number % radix]);
number = number / radix;
}
StringBuilderresult = newStringBuilder();
while (!bits.isEmpty()) {
result.append(bits.pop());
}
returnresult.toString();
}
}