-
Notifications
You must be signed in to change notification settings - Fork 19.4k
/
AnyBaseToDecimal.java
52 lines (47 loc) · 1.7 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
41
42
43
44
45
46
47
48
49
50
51
52
package com.thealgorithms.conversions;
/**
* @author Varun Upadhyay (<a href="https://github.com/varunu28">...</a>)
*/
public final class AnyBaseToDecimal {
private static final int CHAR_OFFSET_FOR_DIGIT = '0';
private static final int CHAR_OFFSET_FOR_UPPERCASE = 'A' - 10;
private AnyBaseToDecimal() {
}
/**
* Convert any radix to a decimal number.
*
* @param input the string to be converted
* @param radix the radix (base) of the input string
* @return the decimal equivalent of the input string
* @throws NumberFormatException if the input string or radix is invalid
*/
public static int convertToDecimal(String input, int radix) {
int result = 0;
int power = 1;
for (int i = input.length() - 1; i >= 0; i--) {
int digit = valOfChar(input.charAt(i));
if (digit >= radix) {
throw new NumberFormatException("For input string: " + input);
}
result += digit * power;
power *= radix;
}
return result;
}
/**
* Convert a character to its integer value.
*
* @param character the character to be converted
* @return the integer value represented by the character
* @throws NumberFormatException if the character is not an uppercase letter or a digit
*/
private static int valOfChar(char character) {
if (Character.isDigit(character)) {
return character - CHAR_OFFSET_FOR_DIGIT;
} else if (Character.isUpperCase(character)) {
return character - CHAR_OFFSET_FOR_UPPERCASE;
} else {
throw new NumberFormatException("invalid character:" + character);
}
}
}