-
Notifications
You must be signed in to change notification settings - Fork 19.7k
/
Copy pathDecimalToBinary.java
49 lines (42 loc) · 1.51 KB
/
DecimalToBinary.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
package com.thealgorithms.conversions;
/**
* This class provides methods to convert a decimal number to a binary number.
*/
final class DecimalToBinary {
private static final int BINARY_BASE = 2;
private static final int DECIMAL_MULTIPLIER = 10;
private DecimalToBinary() {
}
/**
* 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
*/
public static int convertUsingConventionalAlgorithm(int decimalNumber) {
int binaryNumber = 0;
int position = 1;
while (decimalNumber > 0) {
int remainder = decimalNumber % BINARY_BASE;
binaryNumber += remainder * position;
position *= DECIMAL_MULTIPLIER;
decimalNumber /= BINARY_BASE;
}
return binaryNumber;
}
/**
* 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
*/
public static int convertUsingBitwiseAlgorithm(int decimalNumber) {
int binaryNumber = 0;
int position = 1;
while (decimalNumber > 0) {
int leastSignificantBit = decimalNumber & 1;
binaryNumber += leastSignificantBit * position;
position *= DECIMAL_MULTIPLIER;
decimalNumber >>= 1;
}
return binaryNumber;
}
}