題目描述
寫出一個程序,接受一個十六進制的數值字符串,輸出該數值的十進制字符串。(多組同時輸入 )
輸入描述
輸入一個十六進制的數值字符串。
輸出描述
輸出該數值的十進制字符串
輸入例子
0xA
輸出例子
10
算法實現
import java.util.Scanner;
/**
*
* Declaration: All Rights Reserved !!!
*/
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String input = scanner.nextLine();
System.out.println(hexToDec(input));
}
scanner.close();
}
private static int hexToDec(String hex) {
final int BASE = 16;
int result = 0;
for (int i = 2; i < hex.length(); i++) {
result = result * BASE + hexToNum(hex.charAt(i));
}
return result;
}
private static int hexToNum(char ch) {
if (ch >= '0' && ch <= '9') {
return ch - '0';
} else if (ch >= 'a' && ch <= 'z') {
return ch - 'a' + 10;
} else {
return ch - 'A' + 10;
}
}
}