题解 | #进制转换#
进制转换
https://www.nowcoder.com/practice/8f3df50d2b9043208c5eed283d1d4da6
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.on("line", function (line) {
console.log(hexToDecimal(line));
});
function hexToDecimal(hex: string): number {
// 移除十六进制前缀 '0x'(如果存在)
hex = hex.startsWith("0x") ? hex.slice(2) : hex;
const hexDigits = "0123456789ABCDEF";
let decimal = 0;
// 从右往左遍历十六进制字符串
for (let i = hex.length - 1; i >= 0; i--) {
const digit = hexDigits.indexOf(hex[i].toUpperCase());
// 将每位的十六进制位与其相应的权值相乘,然后累加
decimal += digit * Math.pow(16, hex.length - 1 - i);
}
return decimal;
}

