-
Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathAnyBaseToDecimal.java
40 lines (35 loc) · 1.1 KB
/
AnyBaseToDecimal.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
package com.conversions;
public class AnyBaseToDecimal {
/**
* This method produces integer value of the input character and returns it
*
* @param c Char of which we need the integer value of
* @return integer value of input char
*/
private static int valOfChar(char c) {
if (c >= '0' && c <= '9') {
return (int) c - '0';
} else {
return (int) c - 'A' + 10;
}
}
/**
* This method produces a decimal value of any given input number of any base
*
* @param inpNum String of which we need the decimal value and base in integer format
* @return string format of the decimal value
*/
public String convertToDecimal(String inpNum, int base) {
int len = inpNum.length();
int num = 0;
int pow = 1;
for (int i = len - 1; i >= 0; i--) {
if (valOfChar(inpNum.charAt(i)) >= base) {
return "Invalid Number";
}
num += valOfChar(inpNum.charAt(i)) * pow;
pow *= base;
}
return String.valueOf(num);
}
}