Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/main/java/com/thealgorithms/conversions/HexToOct.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ private HexToOct() {
*
* @param hex The Hexadecimal number as a String.
* @return The Decimal equivalent as an integer.
* @throws IllegalArgumentException if the string contains a character that is not a hexadecimal digit
*/
public static int hexToDecimal(String hex) {
String hexDigits = "0123456789ABCDEF";
Expand All @@ -23,6 +24,9 @@ public static int hexToDecimal(String hex) {
for (int i = 0; i < hex.length(); i++) {
char hexChar = hex.charAt(i);
int digitValue = hexDigits.indexOf(hexChar);
if (digitValue == -1) {
throw new IllegalArgumentException("Invalid hexadecimal digit: " + hexChar);
}
decimalValue = 16 * decimalValue + digitValue;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.thealgorithms.conversions;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import org.junit.jupiter.api.Test;

Expand Down Expand Up @@ -30,4 +31,11 @@ public void testHexToOctal() {
assertEquals(0, HexToOct.hexToOctal("0"));
assertEquals(7777, HexToOct.hexToOctal("FFF"));
}

@Test
public void testInvalidHexDigitThrows() {
assertThrows(IllegalArgumentException.class, () -> HexToOct.hexToDecimal("1G"));
assertThrows(IllegalArgumentException.class, () -> HexToOct.hexToDecimal("0x1A"));
assertThrows(IllegalArgumentException.class, () -> HexToOct.hexToOctal("Z"));
}
}
Loading