[LeetCode] Convert a Number to Hexadecimal 数字转为十六进制

简介:

Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.

Note:

  1. All letters in hexadecimal (a-f) must be in lowercase.
  2. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character.
  3. The given number is guaranteed to fit within the range of a 32-bit signed integer.
  4. You must not use any method provided by the library which converts/formats the number to hex directly.

Example 1:

Input:
26
Output:
"1a"

Example 2:

Input:
-1
Output:
"ffffffff"

这道题给了我们一个数字,让我们转化为十六进制,抛开题目,我们应该都会把一个十进制数转为十六进制数,比如50,转为十六进制数,我们先对50除以16,商3余2,那么转为十六进制数就是32。所以我们就按照这个思路来写代码,由于输入数字的大小限制为int型,我们对于负数的处理方法是用其补码来运算,那么数字范围就是0到UINT_MAX,即为16^8-1,那么最高位就是16^7,我们首先除以这个数字,如果商大于等于10,我们用字母代替,否则就是用数字代替,然后对其余数进行同样的处理,一直到当前数字为0停止,最后我们还要补齐末尾的0,方法根据n的值,比-1大多少就补多少个0。由于题目中说明了最高位不能有多余的0,所以我们将起始0移除,如果res为空了,我们就返回0即可,参见代码如下:

解法一:

class Solution {
public:
    string toHex(int num) {
        string res = "";
        vector<string> v{"a","b","c","d","e","f"};
        int n = 7;
        unsigned int x = num;
        if (num < 0) x = UINT_MAX + num + 1;
        while (x > 0) {
            int t = pow(16, n);
            int d = x / t;
            if (d >= 10) res += v[d - 10];
            else if (d >= 0) res += to_string(d);
            x %= t;
            --n;
        }
        while (n-- >= 0) res += to_string(0);
        while (!res.empty() && res[0] == '0') res.erase(res.begin());
        return res.empty() ? "0" : res;
    }
};

上述方法稍稍复杂一些,我们来看一种更简洁的方法,我们采取位操作的思路,每次取出最右边四位,如果其大于等于10,找到对应的字母加入结果,反之则将对应的数字加入结果,然后num像右平移四位,循环停止的条件是num为0,或者是已经循环了7次,参见代码如下:

解法二:

class Solution {
public:
    string toHex(int num) {
        string res = "";
        for (int i = 0; num && i < 8; ++i) {
            int t = num & 0xf;
            if (t >= 10) res = char('a' + t - 10) + res;
            else res = char('0' + t) + res;
            num >>= 4;
        }
        return res.empty() ? "0" : res;
    }
};

下面这种写法更加简洁一些,虽然思路跟解法二并没有什么区别,但是我们把要转换的十六进制的数字字母都放在一个字符串中,按位置直接取就可以了,参见代码如下:

解法三:

class Solution {
public:
    string toHex(int num) {
        string res = "", str = "0123456789abcdef";
        int cnt = 0;
        while (num != 0 && cnt++ < 8) {
            res = str[(num & 0xf)] + res;
            num >>= 4;
        }
        return res.empty() ? "0" : res;
    }
};

本文转自博客园Grandyang的博客,原文链接:数字转为十六进制[LeetCode] Convert a Number to Hexadecimal ,如需转载请自行联系原博主。

相关文章
|
6月前
|
算法
Leetcode 313. Super Ugly Number
题目翻译成中文是『超级丑数』,啥叫丑数?丑数就是素因子只有2,3,5的数,7 14 21不是丑数,因为他们都有7这个素数。 这里的超级丑数只是对丑数的一个扩展,超级丑数的素因子不再仅限于2 3 5,而是由题目给定一个素数数组。与朴素丑数算法相比,只是将素因子变了而已,解法还是和朴素丑数一致的。
65 1
|
6月前
|
存储
Leetcode Single Number II (面试题推荐)
给你一个整数数组,每个元素出现了三次,但只有一个元素出现了一次,让你找出这个数,要求线性的时间复杂度,不使用额外空间。
21 0
LeetCode contest 190 5417. 定长子串中元音的最大数目 Maximum Number of Vowels in a Substring of Given Length
LeetCode contest 190 5417. 定长子串中元音的最大数目 Maximum Number of Vowels in a Substring of Given Length
LeetCode Contest 178-1365. 有多少小于当前数字的数字 How Many Numbers Are Smaller Than the Current Number
LeetCode Contest 178-1365. 有多少小于当前数字的数字 How Many Numbers Are Smaller Than the Current Number
LeetCode 136. 只出现一次的数字 Single Number
LeetCode 136. 只出现一次的数字 Single Number
LeetCode contest 177 5169. 日期之间隔几天 Number of Days Between Two Dates
LeetCode contest 177 5169. 日期之间隔几天 Number of Days Between Two Dates
|
人工智能 算法
LeetCode 1347. 制造字母异位词的最小步骤数 Minimum Number of Steps to Make Two Strings Anagram
LeetCode 1347. 制造字母异位词的最小步骤数 Minimum Number of Steps to Make Two Strings Anagram
LeetCode 1342. 将数字变成 0 的操作次数 Number of Steps to Reduce a Number to Zero
LeetCode 1342. 将数字变成 0 的操作次数 Number of Steps to Reduce a Number to Zero
|
算法
LeetCode 414. Third Maximum Number
给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。要求算法时间复杂度必须是O(n)。
66 0
LeetCode 414. Third Maximum Number
|
算法
LeetCode 405. Convert a Number to Hexadecimal
给定一个整数,编写一个算法将这个数转换为十六进制数。对于负整数,我们通常使用 补码运算 方法。
65 0
LeetCode 405. Convert a Number to Hexadecimal

热门文章

最新文章