405. Convert a Number to Hexadecimal

  • 40.7%

https://leetcode.com/problems/convert-a-number-to-hexadecimal/?tab=Description

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.
1
2
3
4
5
6
7
Example 1:

Input:
26

Output:
"1a"
1
2
3
4
5
6
7
Example 2:

Input:
-1

Output:
"ffffffff"

方法一:

本题中,使用位运算最方便,直接4位4位的前进。

不用纠结它的二位码到底如何,直接位运算,决定结果。

我的代码实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
string toHex(int num) {
if(num==0)
return "0";
vector<string> v = {"0", "1", "2", "3", "4",
"5", "6", "7", "8", "9",
"a", "b", "c", "d",
"e", "f"};
string res;
// 为了对负数有效,加了res.size()<8这个条件
while(num!=0 && res.size()<8){
res = v[num&15] + res;
num = num>>4;
}
return res;
}
};

https://discuss.leetcode.com/topic/60365/simple-java-solution-with-comment

Simple Java solution with comment

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/*
Basic idea: each time we take a look at the last four digits of
binary verion of the input, and maps that to a hex char
shift the input to the right by 4 bits, do it again
until input becomes 0.

*/

public class Solution {

char[] map = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};

public String toHex(int num) {
if(num == 0) return "0";
String result = "";
while(num != 0){
result = map[(num & 15)] + result;
num = (num >>> 4);
}
return result;
}


}

https://discuss.leetcode.com/topic/60365/simple-java-solution-with-comment/2

My corresponding C++ code. I must add result.size()<8 in the while condition, or it will loop forever with a negative input.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
string toHex(int num) {
if (num == 0) return "0";
vector<char> toHexChar = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
string result;
while (num != 0 && result.size()<8){
result = toHexChar[num&15] + result;
num = num >> 4;
}
return result;
}
};

https://discuss.leetcode.com/topic/60365/simple-java-solution-with-comment/3

StringBuilder may be used here.

1
2
3
4
5
6
7
8
9
public String toHex(int num) {
StringBuilder sb = new StringBuilder();
do {
int n = num & 0xf;
n += n < 0xa ? '0' : 'a' - 10;
sb.append((char)n);
} while ((num >>>= 4) != 0);
return sb.reverse().toString();
}

https://discuss.leetcode.com/topic/60431/concise-c-solution

Concise C++ Solution

注意cpp中 双引号和单引号的区别

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const string HEX = "0123456789abcdef";
class Solution {
public:
string toHex(int num) {
if (num == 0) return "0";
string result;
int count = 0;
while (num && count++ < 8) {
result = HEX[(num & 0xf)] + result;
num >>= 4;
}
return result;
}
};

https://discuss.leetcode.com/topic/60929/1-liner-in-python

1-liner in Python

1
2
3
4
5
6
class Solution(object):
def toHex(self, num):
return ''.join(
'0123456789abcdef'[(num >> 4 * i) & 15]
for i in range(8)
)[::-1].lstrip('0') or '0'

https://discuss.leetcode.com/topic/61846/easy-10-line-python-solution-with-inline-explanation

easy 10-line python solution with inline explanation

1
2
3
4
5
6
7
8
9
10
def toHex(self, num):
if num==0: return '0'
mp = '0123456789abcdef' # like a map
ans = ''
for i in range(8):
n = num & 15 # this means num & 1111b
c = mp[n] # get the hex char
ans = c + ans
num = num >> 4
return ans.lstrip('0') #strip leading zeroes

谢谢你,可爱的朋友。