按照公式 result = 个位*1 + 十位*16 + 百位*16^2...
计算即可。
注意初始化一下十六进制各个 char
(0-F)对应的数字。
public class HexToDec {
private static final Map<Character, Integer> charMap = new HashMap();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String hex = in.nextLine();
String result = solution(hex);
System.out.println(result);
}
}
// init map
private static void initMap() {
char tempChar = 'A';
int tempInt = 10;
while (tempChar <= 'F') {
charMap.put(tempChar++, tempInt++);
}
tempChar = '0';
tempInt = 0;
while (tempChar <= '9') {
charMap.put(tempChar++, tempInt++);
}
}
private static String solution(String input) {
// boundary check
if (!input.startsWith("0x") || input.length() <= 2) {
return "";
}
int length = input.length(), i = length, base = 1;
int result = 0;
while (--i >= 2) {
char currentChar = input.charAt(i);
result += charMap.get(currentChar) * base;
base *= 16;
}
return Integer.toString(result);
}
}