问题描述
从键盘输入一个不超过8位的正的十六进制数字符串,将它转换为正的十进制数后输出。
注:十六进制数中的10~15分别用大写的英文字母A、B、C、D、E、F表示。
样例输入
FFFF
样例输出
65535
分析
本题不可以用integer自带的方法转,因为8个F会超出界限,报出NumberFormatException异常,所以需要用其他方法,本题思路,高位*16+低位,直到到个位
~~~
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String str = input.next();
String a[] = new String[str.length()];
for (int i = 0; i < str.length(); i++) {
switch (str.charAt(i)) {
case '1':
a[i] = "1";
break;
case '2':
a[i] = "2";
break;
case '3':
a[i] = "3";
break;
case '4':
a[i] = "4";
break;
case '5':
a[i] = "5";
break;
case '6':
a[i] = "6";
break;
case '7':
a[i] = "7";
break;
case '8':
a[i] = "8";
break;
case '9':
a[i] = "9";
break;
case 'A':
a[i] = "10";
break;
case 'B':
a[i] = "11";
break;
case 'C':
a[i] = "12";
break;
case 'D':
a[i] = "13";
break;
case 'E':
a[i] = "14";
break;
case 'F':
a[i] = "15";
break;
default:
a[i] = "0";
break;
}
}
BigInteger bigInteger = new BigInteger(a[0]);
BigInteger bigInteger2 = new BigInteger("16");
for (int i = 1; i < a.length; i++) {
bigInteger = bigInteger.multiply(bigInteger2).add(new BigInteger(a[i]));
}
System.out.println(bigInteger);
}
}
~~~
备注:还可以用二进制串的方法