题目:进制转换
写出一个程序,接受一个十六进制的数,输出该数值的十进制表示。
数据范围:保证结果在 1≤n≤2的31次方-1
代码实现:
import java.util.Scanner;// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);// 注意 hasNext 和 hasNextLine 的区别String str = in.nextLine();int sum = 0;char[] chararray = str.toCharArray();for (int i = chararray.length - 1; i > 1; i--) {if (chararray[i] == 'A') {int x = chararray.length - 1 - i;int num = 10;if (x == 0) {num = num * 1;sum = sum + num;} else {while (x > 0) {num = num * 16;x--;}sum = sum + num;}} else if (chararray[i] == 'B') {int x = chararray.length - 1 - i;int num = 11;if (x == 0) {num = num * 1;sum = sum + num;} else {while (x > 0) {num = num * 16;x--;}sum = sum + num;}} else if (chararray[i] == 'C') {int x = chararray.length - 1 - i;int num = 12;if (x == 0) {num = num * 1;sum = sum + num;} else {while (x > 0) {num = num * 16;x--;}sum = sum + num;}} else if (chararray[i] == 'D') {int x = chararray.length - 1 - i;int num = 13;if (x == 0) {num = num * 1;sum = sum + num;} else {while (x > 0) {num = num * 16;x--;}sum = sum + num;}} else if (chararray[i] == 'E') {int x = chararray.length - 1 - i;int num = 14;if (x == 0) {num = num * 1;sum = sum + num;} else {while (x > 0) {num = num * 16;x--;}sum = sum + num;}} else if (chararray[i] == 'F') {int x = chararray.length - 1 - i;int num = 15;if (x == 0) {num = num * 1;sum = sum + num;} else {while (x > 0) {num = num * 16;x--;}sum = sum + num;}} else {int x = chararray.length - 1 - i;int num = chararray[i]-48;if (x == 0) {num = num * 1;sum = sum + num;} else {while (x > 0) {num = num * 16;x--;}sum = sum + num;}}}System.out.println(sum);}
}