题解 | #进制转换#

进制转换

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

全部评论

相关推荐

野猪不是猪🐗:现在的环境就是这样,供远大于求。 以前卡学历,现在最高学历不够卡了,还要卡第一学历。 还是不够筛,于是还要求得有实习、不能有gap等等... 可能这个岗位总共就一个hc,筛到最后还是有十几个人满足这些要求。他们都非常优秀,各方面都很棒。 那没办法了,看那个顺眼选哪个呗。 很残酷,也很现实
点赞 评论 收藏
分享
被普调的六边形战士很高大:项目经历貌似和专业或者求职方向没大关系?
点赞 评论 收藏
分享
04-30 15:51
已编辑
上海交通大学 机械工程师
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务