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 pathAnytoAny.java
More file actions
Latest commit
68 lines (61 loc) · 2.27 KB
/
Copy pathAnytoAny.java
File metadata and controls
68 lines (61 loc) · 2.27 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
packagecom.thealgorithms.conversions;
/**
* A utility class for converting numbers from any base to any other base.
*
* This class provides a method to convert a source number from a given base
* to a destination number in another base. Valid bases range from 2 to 10.
*/
publicfinalclassAnytoAny {
privateAnytoAny() {
}
/**
* Converts a number from a source base to a destination base.
*
* @param sourceNumber The number in the source base (as an integer).
* @param sourceBase The base of the source number (between 2 and 10).
* @param destBase The base to which the number should be converted (between 2 and 10).
* @throws IllegalArgumentException if the bases are not between 2 and 10.
* @return The converted number in the destination base (as an integer).
*/
publicstaticintconvertBase(intsourceNumber, intsourceBase, intdestBase) {
if (sourceBase < 2 || sourceBase > 10 || destBase < 2 || destBase > 10) {
thrownewIllegalArgumentException("Bases must be between 2 and 10.");
}
intdecimalValue = toDecimal(sourceNumber, sourceBase);
returnfromDecimal(decimalValue, destBase);
}
/**
* Converts a number from a given base to its decimal representation (base 10).
*
* @param number The number in the original base.
* @param base The base of the given number.
* @return The decimal representation of the number.
*/
privatestaticinttoDecimal(intnumber, intbase) {
intdecimalValue = 0;
intmultiplier = 1;
while (number != 0) {
decimalValue += (number % 10) * multiplier;
multiplier *= base;
number /= 10;
}
returndecimalValue;
}
/**
* Converts a decimal (base 10) number to a specified base.
*
* @param decimal The decimal number to convert.
* @param base The destination base for conversion.
* @return The number in the specified base.
*/
privatestaticintfromDecimal(intdecimal, intbase) {
intresult = 0;
intmultiplier = 1;
while (decimal != 0) {
result += (decimal % base) * multiplier;
multiplier *= 10;
decimal /= base;
}
returnresult;
}
}