|
| 1 | +package DataStructures.Stacks; |
| 2 | + |
| 3 | +import java.util.Stack; |
| 4 | + |
| 5 | +public class DecimalToAnyUsingStack { |
| 6 | + public static void main(String[] args) { |
| 7 | + assert convert(0, 2).equals("0"); |
| 8 | + assert convert(30, 2).equals("11110"); |
| 9 | + assert convert(30, 8).equals("36"); |
| 10 | + assert convert(30, 10).equals("30"); |
| 11 | + assert convert(30, 16).equals("1E"); |
| 12 | + } |
| 13 | + |
| 14 | + /** |
| 15 | + * Convert decimal number to another radix |
| 16 | + * |
| 17 | + * @param number the number to be converted |
| 18 | + * @param radix the radix |
| 19 | + * @return another radix |
| 20 | + * @throws ArithmeticException if <tt>number</tt> or <tt>radius</tt> is invalid |
| 21 | + */ |
| 22 | + private static String convert(int number, int radix) { |
| 23 | + if (radix < 2 || radix > 16) { |
| 24 | + throw new ArithmeticException( |
| 25 | + String.format("Invalid input -> number:%d,radius:%d", number, radix)); |
| 26 | + } |
| 27 | + char[] tables = { |
| 28 | + '0', '1', '2', '3', '4', |
| 29 | + '5', '6', '7', '8', '9', |
| 30 | + 'A', 'B', 'C', 'D', 'E', 'F' |
| 31 | + }; |
| 32 | + Stack<Character> bits = new Stack<>(); |
| 33 | + do { |
| 34 | + bits.push(tables[number % radix]); |
| 35 | + number = number / radix; |
| 36 | + } while (number != 0); |
| 37 | + |
| 38 | + StringBuilder result = new StringBuilder(); |
| 39 | + while (!bits.isEmpty()) { |
| 40 | + result.append(bits.pop()); |
| 41 | + } |
| 42 | + return result.toString(); |
| 43 | + } |
| 44 | +} |
0 commit comments