描述
写出一个程序,接受一个十六进制的数,输出该数值的十进制表示。
数据范围:保证结果在 1 \le n \le 2^{31}-1 \1≤n≤231−1
输入描述:
输入一个十六进制的数值字符串。
输出描述:
输出该数值的十进制字符串。不同组的测试用例用\n隔开。
示例1
import java.util.Scanner;
/**
*author:向敏
*date:2022-04-18
**/
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;
}
}
}