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 pathDecimalToBinary.java
More file actions
Latest commit
49 lines (42 loc) · 1.51 KB
/
Copy pathDecimalToBinary.java
File metadata and controls
49 lines (42 loc) · 1.51 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
packagecom.thealgorithms.conversions;
/**
* This class provides methods to convert a decimal number to a binary number.
*/
finalclassDecimalToBinary {
privatestaticfinalintBINARY_BASE = 2;
privatestaticfinalintDECIMAL_MULTIPLIER = 10;
privateDecimalToBinary() {
}
/**
* Converts a decimal number to a binary number using a conventional algorithm.
* @param decimalNumber the decimal number to convert
* @return the binary representation of the decimal number
*/
publicstaticintconvertUsingConventionalAlgorithm(intdecimalNumber) {
intbinaryNumber = 0;
intposition = 1;
while (decimalNumber > 0) {
intremainder = decimalNumber % BINARY_BASE;
binaryNumber += remainder * position;
position *= DECIMAL_MULTIPLIER;
decimalNumber /= BINARY_BASE;
}
returnbinaryNumber;
}
/**
* Converts a decimal number to a binary number using a bitwise algorithm.
* @param decimalNumber the decimal number to convert
* @return the binary representation of the decimal number
*/
publicstaticintconvertUsingBitwiseAlgorithm(intdecimalNumber) {
intbinaryNumber = 0;
intposition = 1;
while (decimalNumber > 0) {
intleastSignificantBit = decimalNumber & 1;
binaryNumber += leastSignificantBit * position;
position *= DECIMAL_MULTIPLIER;
decimalNumber >>= 1;
}
returnbinaryNumber;
}
}