|
| 1 | +import java.io.BufferedReader; |
| 2 | +import java.io.InputStreamReader; |
| 3 | +import java.util.ArrayList; |
| 4 | + |
| 5 | +/** |
| 6 | + * |
| 7 | + * @author Varun Upadhyay (https://github.com/varunu28) |
| 8 | + * |
| 9 | + */ |
| 10 | + |
| 11 | +// Driver Program |
| 12 | +public class DecimalToAnyBase { |
| 13 | + public static void main (String[] args) throws Exception{ |
| 14 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 15 | + System.out.println("Enter the decimal input below: "); |
| 16 | + int decInput = Integer.parseInt(br.readLine()); |
| 17 | + System.out.println(); |
| 18 | + |
| 19 | + System.out.println("Enter the base below: "); |
| 20 | + int base = Integer.parseInt(br.readLine()); |
| 21 | + System.out.println(); |
| 22 | + |
| 23 | + System.out.println("Decimal Input" + " is: " + decInput); |
| 24 | + System.out.println("Value of " + decInput + " in base " + base + " is: " + convertToAnyBase(decInput, base)); |
| 25 | + |
| 26 | + br.close(); |
| 27 | + } |
| 28 | + |
| 29 | + /** |
| 30 | + * This method produces a String value of any given input decimal in any base |
| 31 | + * @param inp Decimal of which we need the value in base in String format |
| 32 | + * @return string format of the converted value in the given base |
| 33 | + */ |
| 34 | + |
| 35 | + public static String convertToAnyBase(int inp, int base) { |
| 36 | + ArrayList<Character> charArr = new ArrayList<>(); |
| 37 | + |
| 38 | + while (inp > 0) { |
| 39 | + charArr.add(reVal(inp%base)); |
| 40 | + inp /= base; |
| 41 | + } |
| 42 | + |
| 43 | + StringBuilder str = new StringBuilder(charArr.size()); |
| 44 | + |
| 45 | + for(Character ch: charArr) |
| 46 | + { |
| 47 | + str.append(ch); |
| 48 | + } |
| 49 | + |
| 50 | + return str.reverse().toString(); |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * This method produces character value of the input integer and returns it |
| 55 | + * @param num integer of which we need the character value of |
| 56 | + * @return character value of input integer |
| 57 | + */ |
| 58 | + |
| 59 | + public static char reVal(int num) { |
| 60 | + if (num >= 0 && num <= 9) |
| 61 | + return (char)(num + '0'); |
| 62 | + else |
| 63 | + return (char)(num - 10 + 'A'); |
| 64 | + } |
| 65 | +} |
0 commit comments