[Leetcode] 405. Convert a Number to Hexadecimal 解题报告

来源:互联网 发布:尚硅谷java视频教程 编辑:程序博客网 时间:2024/06/14 00:40

题目

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:26Output:"1a"

Example 2:

Input:-1Output:"ffffffff"

思路

由于16是2的次幂,并且整数在计算机中都是以二进制的形式表示的,所以转化为16进制的方法非常简单:每次获得二进制的最低4位,直接将其转换为16进制的表示即可。在C++中实现需要注意的一点是:由于有符号整数和无符号整数在负数情况下的循环移位有所不同,所以我们在对num进行循环移位前,需要首先将其显式转换为无符号整数,这样可以统一处理正整数和负整数。

这道题目虽然也可以用传统的除余法解决,但是代码就相对复杂多了,而且处理补码的情况比较麻烦。

代码

class Solution {public:    string toHex(int num) {        string ret("");        string hex_chars("0123456789abcdef");        while (num) {            ret.push_back(hex_chars[num & 0xF]);            num = (unsigned)num >> 4;        }        reverse(ret.begin(), ret.end());        return ret.empty() ? "0" : ret;    }};

阅读全文
0 0
原创粉丝点击