Skip to content

Commit 68b91ce

Browse files
committed
Fix
1 parent 58ef9b4 commit 68b91ce

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

src/main/java/com/thealgorithms/conversions/BCDConverter.java

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,28 @@ public static String decimalToBCD(int number) {
2525
StringBuilder bcd = new StringBuilder();
2626
while (number > 0) {
2727
int digit = number % 10;
28-
bcd.insert(0, String.format("%04d", Integer.parseInt(Integer.toString(digit, 2))));
28+
bcd.insert(0, String.format("%04d", convertToBinary(digit)));
2929
number /= 10;
3030
}
3131
return bcd.toString();
3232
}
3333

34+
/**
35+
* Converts a single digit to its 4-bit binary representation.
36+
* @param digit the digit to convert (0-9).
37+
* @return the binary representation as an int.
38+
*/
39+
private static int convertToBinary(int digit) {
40+
int binary = 0;
41+
int multiplier = 1;
42+
while (digit > 0) {
43+
binary += (digit % 2) * multiplier;
44+
digit /= 2;
45+
multiplier *= 10;
46+
}
47+
return binary;
48+
}
49+
3450
/**
3551
* Converts a BCD string back to its decimal representation.
3652
* @param bcd the BCD string to convert.

0 commit comments

Comments
 (0)