- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathDecimalToAnyUsingStack.java
60 lines (55 loc) · 1.54 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
packagecom.thealgorithms.stacks;
importjava.util.Stack;
publicfinalclassDecimalToAnyUsingStack {
privateDecimalToAnyUsingStack() {
}
publicstaticvoidmain(String[] args) {
assertconvert(0, 2).equals("0");
assertconvert(30, 2).equals("11110");
assertconvert(30, 8).equals("36");
assertconvert(30, 10).equals("30");
assertconvert(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
*/
privatestaticStringconvert(intnumber, intradix) {
if (radix < 2 || radix > 16) {
thrownewArithmeticException(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 = newStack<>();
do {
bits.push(tables[number % radix]);
number = number / radix;
} while (number != 0);
StringBuilderresult = newStringBuilder();
while (!bits.isEmpty()) {
result.append(bits.pop());
}
returnresult.toString();
}
}