Interview Question
SDE-2sCountry: United States
//java8
int convertFromHex(char[] s) {
int digit, result = 0, i = (s[0] == '0') && (s[1] == 'x' || s[1] == 'X') ? 2 : 0;
for (; i < s.length; i++) {
char c = s[i];
if (c >= '0' && c <= '9') {
digit = c - '0';
} else if (c >= 'A' && c <= 'F') {
digit = 10 + c - 'A';
} else {
throw new IllegalArgumentException("not hex");
}
try {
result =
Math.addExact(Math.multiplyExact(16, result),
digit);
} catch (Exception e) {
throw new IllegalArgumentException("overflow", e);
}
}
return result;
}
public class HexToDecimal {
public static void main(String[] args) {
System.out.println(convertFromHex("36F9BFB3"));
}
static int convertFromHex(String str) {
char[] s = str.toUpperCase().toCharArray();
int digit, result = 0, i = (s[0] == '0') && s[1] == 'X' ? 2 : 0;
for (; i < s.length; i++) {
char c = s[i];
if (c >= '0' && c <= '9') {
digit = c - '0';
} else if (c >= 'A' && c <= 'F') {
digit = 10 + c - 'A';
} else {
throw new IllegalArgumentException("not hex");
}
try {
result =
Math.addExact(Math.multiplyExact(16, result),
digit);
} catch (Exception e) {
throw new IllegalArgumentException("overflow", e);
}
}
return result;
}
}
for this simple questions, make sure all border cases, overflows, etc. are covered.
as well, maybe define the allowed token/string exactly (e.g. using regexp)
that would be "\s*0x[0-9a-zA-Z]+\s*"
- Chris August 23, 2017