This is code from Cracking the Coding Interview 5th Edition I got this from https://code.google.com/p/ctci/source/browse/trunk/Java/Introduction/CompareBinaryToHex/CompareBinaryToHex.java?spec=svn18&r=3 (didn't want to take and upload a picture of a few pages from the book) Here's the code
public class CompareBinaryToHex {
public static int digitToValue(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'A' && c <= 'F') {
return 10 + c - 'A';
} else if (c >= 'a' && c <= 'f') {
return 10 + c - 'a';
}
return -1;
}
public static int convertToBase(String number, int base) {
if (base < 2 || (base > 10 && base != 16)) return -1;
int value = 0;
for (int i = number.length() - 1; i >= 0; i--) {
int digit = digitToValue(number.charAt(i));
if (digit < 0 || digit >= base) {
return -1;
}
int exp = number.length() - 1 - i;
value += digit * Math.pow(base, exp);
}
return value;
}
public static boolean compareBinToHex(String binary, String hex) {
int n1 = convertToBase(binary, 2);
int n2 = convertToBase(hex, 16);
if (n1 < 0 || n2 < 0) {
return false;
} else {
return n1 == n2;
}
}
public static void main(String[] args) {
System.out.println(compareBinToHex("111001011", "1CB"));
}
}
Basically a method inside this class compareBinToHex, takes in String representations of a binary number and a hex number and returns whether or not they are equal or not(in decimal value). It uses the method convertToBase to convert from that base to decimal. My question is for the convertToBase method, why are base inputs in the range 2-9 and 16 allowed, but base inputs from 11-15 are not? (Base inputs in range 2-9 and 16 will not go in the return -1 if block) Gayle, the author later summarized that it's better to write code that is more flexible and general-purpose which I would agree with and is the reasoning behind my argument for the allowance of 11-15 base inputs. Say if you're working with base 11. I believe convertToBase should still work for this because you're counting to 'A' which should still work behind the logic(range 'A' to 'F') in digitToValue. Is there a reason why she disallowed those inputs?
Because very few people need a base (or radix) 11, 12, 13, 14 or 15 calculator. It's important to note that base 8 is octal, base 2 is binary, base 10 is decimal and base 16 is hexadecimal. I would go further and suggest you explicitly check it's one of those,
if (base != 2 && base != 8 && base != 10 && base != 16) return -1;