题解 | #进制转换#
package 华为.字符串;
import java.util.Scanner;
public class 进制转换 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
//输入16进制的字符串
String s = sc.nextLine();
//输入十进制结果
System.out.println(convert(s));
}
}
private static int convert(String s) { int len = s.length(); int index = 0; int sum = 0; char[] chs = s.toCharArray(); for (int i = len-1; i >= 2; i--) { char ch = chs[i]; sum = (int) (sum + Math.pow(16, index)*switchTen(ch)); index += 1; } return sum; } private static int switchTen(char ch) { switch (ch) { case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'A': return 10; case 'B': return 11; case 'C': return 12; case 'D': return 13; case 'E': return 14; case 'F': return 15; default: break; } return -1; }
}