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 pathDecimalToAnyBase.java
More file actions
Latest commit
69 lines (60 loc) · 2.47 KB
/
Copy pathDecimalToAnyBase.java
File metadata and controls
69 lines (60 loc) · 2.47 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
packagecom.thealgorithms.conversions;
importjava.util.ArrayList;
importjava.util.List;
/**
* Class that provides methods to convert a decimal number to a string representation
* in any specified base between 2 and 36.
*
* @author Varun Upadhyay (<a href="https://github.com/varunu28">...</a>)
*/
publicfinalclassDecimalToAnyBase {
privatestaticfinalintMIN_BASE = 2;
privatestaticfinalintMAX_BASE = 36;
privatestaticfinalcharZERO_CHAR = '0';
privatestaticfinalcharA_CHAR = 'A';
privatestaticfinalintDIGIT_OFFSET = 10;
privateDecimalToAnyBase() {
}
/**
* Converts a decimal number to a string representation in the specified base.
* For example, converting the decimal number 10 to base 2 would return "1010".
*
* @param decimal the decimal number to convert
* @param base the base to convert to (must be between {@value #MIN_BASE} and {@value #MAX_BASE})
* @return the string representation of the number in the specified base
* @throws IllegalArgumentException if the base is out of the supported range
*/
publicstaticStringconvertToAnyBase(intdecimal, intbase) {
if (base < MIN_BASE || base > MAX_BASE) {
thrownewIllegalArgumentException("Base must be between " + MIN_BASE + " and " + MAX_BASE);
}
if (decimal == 0) {
returnString.valueOf(ZERO_CHAR);
}
List<Character> digits = newArrayList<>();
while (decimal > 0) {
digits.add(convertToChar(decimal % base));
decimal /= base;
}
StringBuilderresult = newStringBuilder(digits.size());
for (inti = digits.size() - 1; i >= 0; i--) {
result.append(digits.get(i));
}
returnresult.toString();
}
/**
* Converts an integer value to its corresponding character in the specified base.
* This method is used to convert values from 0 to 35 into their appropriate character representation.
* For example, 0-9 are represented as '0'-'9', and 10-35 are represented as 'A'-'Z'.
*
* @param value the integer value to convert (should be less than the base value)
* @return the character representing the value in the specified base
*/
privatestaticcharconvertToChar(intvalue) {
if (value >= 0 && value <= 9) {
return (char) (ZERO_CHAR + value);
} else {
return (char) (A_CHAR + value - DIGIT_OFFSET);
}
}
}