|
| 1 | +import java.io.BufferedReader; |
| 2 | +import java.io.InputStreamReader; |
| 3 | + |
| 4 | +/** |
| 5 | + * |
| 6 | + * @author Varun Upadhyay (https://github.com/varunu28) |
| 7 | + * |
| 8 | + */ |
| 9 | + |
| 10 | +// Driver program |
| 11 | +public class AnyBaseToDecimal { |
| 12 | + public static void main (String[] args) throws Exception{ |
| 13 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 14 | + |
| 15 | + String inp = br.readLine(); |
| 16 | + int base = Integer.parseInt(br.readLine()); |
| 17 | + |
| 18 | + System.out.println("Input in base " + base + " is: " + inp); |
| 19 | + System.out.println("Decimal value of " + inp + " is: " + convertToDecimal(inp, base)); |
| 20 | + |
| 21 | + br.close(); |
| 22 | + } |
| 23 | + |
| 24 | + /** |
| 25 | + * This method produces a decimal value of any given input number of any base |
| 26 | + * @param inp_num String of which we need the decimal value and base in integer format |
| 27 | + * @return string format of the decimal value |
| 28 | + */ |
| 29 | + |
| 30 | + public static String convertToDecimal(String inp_num, int base) { |
| 31 | + int len = inp_num.length(); |
| 32 | + int num = 0; |
| 33 | + int pow = 1; |
| 34 | + |
| 35 | + for (int i=len-1; i>=0; i--) { |
| 36 | + if (valOfChar(inp_num.charAt(i)) >= base) { |
| 37 | + return "Invalid Number"; |
| 38 | + } |
| 39 | + num += valOfChar(inp_num.charAt(i))*pow; |
| 40 | + pow *= base; |
| 41 | + } |
| 42 | + return String.valueOf(num); |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * This method produces integer value of the input character and returns it |
| 47 | + * @param c Char of which we need the integer value of |
| 48 | + * @return integer value of input char |
| 49 | + */ |
| 50 | + |
| 51 | + public static int valOfChar(char c) { |
| 52 | + if (c >= '0' && c <= '9') { |
| 53 | + return (int)c - '0'; |
| 54 | + } |
| 55 | + else { |
| 56 | + return (int)c - 'A' + 10; |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments