LeetCode每日一题|405.数字转换为十六进制

250 阅读1分钟
  • 题目描述

题目链接:leetcode-cn.com/problems/co… image.png

  • 思路分析

对于一个十其他进制,只需要除以要转化的进制,并取余数放在答案的第一位即可,因为该题为16进制,所以可以先设置一个字符数组来表示16进制的每一位数,以每次得到的余数作为数组下标。对于负数,先将其转换为其补码表示的正数值再进行计算,已知数据为32位数所以只需要将负数加上2**32即可。

  • 代码

var toHex = function (num) {
  if (num == 0) {
    return "0";
  }
  if (num < 0) {
    num = 4294967296 + num;
  }
  let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
  let res = '';
  while (num) {
    res = arr[num % 16] + res;
    num = Math.floor(num / 16);
  }
  return res;
};
  • 其他

直接通过字符码计算得到应添加的字符可以不用先定义数组。

var toHex = function (num) {
  if (num == 0) {
    return "0";
  }
  if (num < 0) {
    num = 4294967296 + num;
  }
  let res = '';
  while (num) {
    let t = num % 16;
    res = (t > 9 ? String.fromCodePoint(t + 87) : String.fromCodePoint(t + 48)) + res;
    num = Math.floor(num / 16);
  }
  return res;
};