Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 21.3k
Expand file tree
/
Copy pathAnyBaseToDecimal.java
More file actions
Latest commit
52 lines (47 loc) · 1.7 KB
/
Copy pathAnyBaseToDecimal.java
File metadata and controls
52 lines (47 loc) · 1.7 KB
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
packagecom.thealgorithms.conversions;
/**
* @author Varun Upadhyay (<a href="https://github.com/varunu28">...</a>)
*/
publicfinalclassAnyBaseToDecimal {
privatestaticfinalintCHAR_OFFSET_FOR_DIGIT = '0';
privatestaticfinalintCHAR_OFFSET_FOR_UPPERCASE = 'A' - 10;
privateAnyBaseToDecimal() {
}
/**
* 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
*/
publicstaticintconvertToDecimal(Stringinput, intradix) {
intresult = 0;
intpower = 1;
for (inti = input.length() - 1; i >= 0; i--) {
intdigit = valOfChar(input.charAt(i));
if (digit >= radix) {
thrownewNumberFormatException("For input string: " + input);
}
result += digit * power;
power *= radix;
}
returnresult;
}
/**
* 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
*/
privatestaticintvalOfChar(charcharacter) {
if (Character.isDigit(character)) {
returncharacter - CHAR_OFFSET_FOR_DIGIT;
} elseif (Character.isUpperCase(character)) {
returncharacter - CHAR_OFFSET_FOR_UPPERCASE;
} else {
thrownewNumberFormatException("invalid character:" + character);
}
}
}