题解 | #进制转换#
进制转换
https://www.nowcoder.com/practice/8f3df50d2b9043208c5eed283d1d4da6
import java.util.Scanner; import java.util.Stack; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); char[] hexChars = in.nextLine().toUpperCase().toCharArray(); Stack<Character> bucket = new Stack<>(); int result = 0; for (int i = 2; i < hexChars.length; i++) { // 从最大位开始压栈 bucket.push(hexChars[i]); } // 开始弹栈,并累计数量,我们需要一个16^0, 16^1, 16^2...的计数器 int unit = 1; while (!bucket.isEmpty()) { result += unit * getDec(bucket.pop()); unit *= 16; } System.out.println(result); } // 此部分使用switch遍历,用Map也可,总之代码量在这里很大 private static int getDec(char hex) { int dec; switch (hex) { case '0' : dec = 0; break; case '1' : dec = 1; break; case '2' : dec = 2; break; case '3' : dec = 3; break; case '4' : dec = 4; break; case '5' : dec = 5; break; case '6' : dec = 6; break; case '7' : dec = 7; break; case '8' : dec = 8; break; case '9' : dec = 9; break; case 'A' : dec = 10; break; case 'B' : dec = 11; break; case 'C' : dec = 12; break; case 'D' : dec = 13; break; case 'E' : dec = 14; break; case 'F' : dec = 15; break; default : dec = -1; } return dec; } }