Skip to content

Commit 4a436c9

Browse files
committed
Fix
1 parent 7780738 commit 4a436c9

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

src/main/java/com/thealgorithms/bitmanipulation/BcdConversion.java

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,19 +24,26 @@ private BcdConversion() {
2424
/**
2525
* Converts a BCD (Binary-Coded Decimal) number to binary.
2626
* <p>Steps:
27-
* <p>1. Extract the last 4 bits (one BCD digit) from the BCD number.
28-
* <p>2. Multiply the extracted digit by the corresponding power of 10 and add it to the binary number.
29-
* <p>3. Shift the BCD number right by 4 bits to process the next BCD digit.
30-
* <p>4. Repeat steps 1-3 until the BCD number is zero.
27+
* <p>1. Validate the BCD number to ensure all digits are between 0 and 9.
28+
* <p>2. Extract the last 4 bits (one BCD digit) from the BCD number.
29+
* <p>3. Multiply the extracted digit by the corresponding power of 10 and add it to the binary number.
30+
* <p>4. Shift the BCD number right by 4 bits to process the next BCD digit.
31+
* <p>5. Repeat steps 1-4 until the BCD number is zero.
3132
*
3233
* @param bcd The BCD number.
3334
* @return The corresponding binary number.
35+
* @throws IllegalArgumentException if the BCD number contains invalid digits.
3436
*/
3537
public static int bcdToBinary(int bcd) {
3638
int binary = 0;
3739
int multiplier = 1;
40+
41+
// Validate BCD digits
3842
while (bcd > 0) {
3943
int digit = bcd & 0xF;
44+
if (digit > 9) {
45+
throw new IllegalArgumentException("Invalid BCD digit: " + digit);
46+
}
4047
binary += digit * multiplier;
4148
multiplier *= 10;
4249
bcd >>= 4;

0 commit comments

Comments
 (0)