I am completely stumped on this one. I have to utilize the current code structure to convert a user-entered hexadecimal value into a decimal value using recursion. The method header for the recursive call cannot be changed. I have this figured out without the use of recursion, but for the life of me cannot wrap my head around how I would do this.
// EDIT — SOLVED
public class hextodecimal {
public static void main(String[] args) {
// Test out the parsing with values from page 719
System.out.println(hexToDecimal("7F"));
System.out.println(hexToDecimal("FFFF"));
System.out.println(hexToDecimal("431"));
}
public static int hexToDecimal(String hexString) {
return hexToDecimal(hexString, 0, hexString.length() - 1);
}
public static int hexToDecimal(String hexString, int end, int hexLength) {
if (hexLength < end)
return 0;
else {
int decValue;
if (hexString.charAt(hexLength) == 'A')
decValue = 10;
else if (hexString.charAt(hexLength) == 'B')
decValue = 11;
else if (hexString.charAt(hexLength) == 'C')
decValue = 12;
else if (hexString.charAt(hexLength) == 'D')
decValue = 13;
else if (hexString.charAt(hexLength) == 'E')
decValue = 14;
else if (hexString.charAt(hexLength) == 'F')
decValue = 15;
else
decValue = hexString.charAt(hexLength) - '0';
return hexToDecimal(hexString, end, hexLength - 1) * 16
+ decValue;
}
}
}
Only two choices. Process the leftmost char, and pass substring(1) to yourself recursively, or process the rightmost char, and pass what’s to the left to yourself recursively. That should be enough of a hint.