405. Convert a Number to Hexadecimal

作者 汪小祯 日期 2017-02-02
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.

Note:

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.
You must not use any method provided by the library which converts/formats the number to hex directly.

思路

优解中采用的方法是直接将十进制转换为2进制
然后再变成十六进制

题解 优解

class Solution {
public:
string toHex(int num) {
if (num == 0) return "0";
string HEX = "0123456789abcdef";
string result;
int time=0;
while (num && time++<8) {//题目要求32位整数范围
result=HEX[num&15]+result;
num>>=4;//将十进制转换为二进制,然后转换为16进制,举例,十进制15,转换为二进制1111,再转为十六进制f,然后右移4位
}
return result;
}
};