题解 | #进制转换#

进制转换

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;
}

全部评论

相关推荐

之前自己不懂事,投了字节,基本是自己第一次面试,一面就挂了
观水:前几天有个学化学的做前端,加上实习面了22次字节最后成功了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务