美文网首页
[刷题防痴呆] 0405 - 数字转换为十六进制数 (Conve

[刷题防痴呆] 0405 - 数字转换为十六进制数 (Conve

作者: 西出玉门东望长安 | 来源:发表于2021-11-09 01:26 被阅读0次

题目地址

https://leetcode.com/problems/convert-a-number-to-hexadecimal/

题目描述

405. Convert a Number to Hexadecimal

Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used.

All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.

Note: You are not allowed to use any built-in library method to directly solve this problem.

 

Example 1:

Input: num = 26
Output: "1a"
Example 2:

Input: num = -1
Output: "ffffffff"

思路

  • 每次与0x0F与操作. 得到的值查表.
  • 相当于每次num的最低位被转换成十六进制.
  • 之后无符号右移4位.
  • 如此往复.

关键点

  • 注意, 从最低位开始转换, 因此注意输出顺序.

代码

  • 语言支持:Java
class Solution {
    public String toHex(int num) {
        if (num == 0) {
            return "0";
        }
        StringBuffer sb = new StringBuffer();
        char[] map = "0123456789abcdef".toCharArray();
        while (num != 0) {
            int index = num & (0x0f);
            sb.append(map[index]);
            num >>>= 4;
        }

        return sb.reverse().toString();
    }
}

相关文章

网友评论

      本文标题:[刷题防痴呆] 0405 - 数字转换为十六进制数 (Conve

      本文链接:https://www.haomeiwen.com/subject/lizyzltx.html