LeetCode 405. Convert a Number to Hexadecimal 解题报告

来源:互联网 发布:快递助手打印软件 编辑:程序博客网 时间:2024/06/06 04:56

LeetCode 405. 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.
- All letters in hexadecimal (a-f) must be in lowercase.
- 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.
- The given number is guaranteed to fit within the range of a 32-bit signed integer.


示例

Example 1:
Input:
26
Output:
“1a”

Example 2:
Input:
-1
Output:
“ffffffff”


限制条件

You must not use any method provided by the library which converts/formats the number to hex directly.


解题思路

我的思路:

对于0,直接返回字符串”0”
对于负数,先进行预处理,位取反后加1
然后使用一个位掩码,每次获取数字的最高4位,通过移位,变回[0-15]之间的数,以此作为下标,得到对应的十六进制表示,添加到结果字符串中。
描述起来似乎挺简单的,但是实现的时候,真是障碍重重,由于没有深刻理解负数在计算机中表示原理,调试了好久才Accept。
按照惯例,自己通过了之后就看看其他人的写法,大牛就是大牛,各种简洁的解法让我眼前一亮。下面是我参考了其它大牛的解法后,修改出来的,算是比较简练的解法。

参考思路:

尽管题目说了负数是用了2补数,但是我们要知道数的二进制表示是不变的,比如-1,它的二进制表示就是32个1,或写成16进制的ffff ffff。因此,无论是正负数都可以直接进行操作,不用预处理(所以我的解法里的预处理多余了)。
处理的过程就是每次获取最低4位,将其对应的16进制表示添加到结果字符串的开头。关键的一点是,进行循环移位时,需要把数转为无符号数进行移位,因为右移操作符添加的值依赖于运算对象的类型,如果是无符号数,则添加0,否则添加符号位的副本或是0,根据具体环境而定。这里我们希望的是添加0,以便用于判断循环结束,所以进行了类型转换。


代码

我的代码

class Solution {public:    string toHex(int num) {        string h = "";        char hexChar[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};        unsigned int mask = 0xF << 28;        unsigned int num_ = num;        if (num == 0)            return "0";        if (num < 0) {            num_ = abs(num);            num_ = ~num_ + 1;        }        for (int i = 7; i >= 0; i--) {            unsigned int n = num_ & mask;            while (n >= 16) {                n = n >> 4;            }            if ((h == "" && n > 0) ||(h.length() > 0)) {                h += hexChar[n];            }            mask = mask >> 4;        }        return h;    }};

参考代码

class Solution {public:    string toHex(int num) {        string hexString = "";        string hexChar = "0123456789abcdef";        while (num) {            hexString = hexChar[num & 0xF] + hexString;            num = (unsigned)num >> 4;        }        return hexString.empty() ? "0" : hexString;    }};

总结

通过这道题,我复习了一下关于位运算及负数表示的知识,同时也从其它人的代码里学到了一些简洁的表示方式,比如16进制字符的添加就可以用string的+运算完成,以后要多注意自己的代码风格,要灵活多变一些。
今天填坑完毕,明天继续,加油加油!

0 0
原创粉丝点击