File tree 1 file changed +10
-4
lines changed
src/main/java/com/thealgorithms/bitmanipulation 1 file changed +10
-4
lines changed Original file line number Diff line number Diff line change @@ -54,15 +54,21 @@ public static int bcdToBinary(int bcd) {
54
54
/**
55
55
* Converts a binary number to BCD (Binary-Coded Decimal).
56
56
* <p>Steps:
57
- * <p>1. Extract the last decimal digit from the binary number.
58
- * <p>2. Shift the digit to the correct BCD position and add it to the BCD number.
59
- * <p>3. Remove the last decimal digit from the binary number.
60
- * <p>4. Repeat steps 1-3 until the binary number is zero.
57
+ * <p>1. Check if the binary number is within the valid range for BCD (0 to 9999).
58
+ * <p>2. Extract the last decimal digit from the binary number.
59
+ * <p>3. Shift the digit to the correct BCD position and add it to the BCD number.
60
+ * <p>4. Remove the last decimal digit from the binary number.
61
+ * <p>5. Repeat steps 2-4 until the binary number is zero.
61
62
*
62
63
* @param binary The binary number.
63
64
* @return The corresponding BCD number.
65
+ * @throws IllegalArgumentException if the binary number is greater than 9999.
64
66
*/
65
67
public static int binaryToBcd (int binary ) {
68
+ if (binary < 0 || binary > 9999 ) {
69
+ throw new IllegalArgumentException ("Value out of bounds for BCD representation: " + binary );
70
+ }
71
+
66
72
int bcd = 0 ;
67
73
int shift = 0 ;
68
74
while (binary > 0 ) {
You can’t perform that action at this time.
0 commit comments