405. Convert a Number to Hexadecimal #
Problem #
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.
Example 1:
Input:
26
Output:
"1a"
Example 2:
Input:
-1
Output:
"ffffffff"
Problem Summary #
Given an integer, write an algorithm to convert this number to hexadecimal. For negative integers, we usually use the two’s complement method.
Note:
- All letters in hexadecimal (a-f) must be lowercase.
- The hexadecimal string must not contain extra leading zeros. If the number to be converted is 0, it is represented by a single character ‘0’; otherwise, the first character in the hexadecimal string will not be the 0 character.
- The given number is guaranteed to be within the range of a 32-bit signed integer.
- You must not use any library-provided method that directly converts or formats the number to hexadecimal.
Solution Ideas #
- This problem is easy: convert a decimal number into a hexadecimal number. Extra attention is needed for the cases of 0 and negative numbers.
Code #
package leetcode
func toHex(num int) string {
if num == 0 {
return "0"
}
if num < 0 {
num += 1 << 32
}
mp := map[int]string{
0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9",
10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f",
}
var bitArr []string
for num > 0 {
bitArr = append(bitArr, mp[num%16])
num /= 16
}
str := ""
for i := len(bitArr) - 1; i >= 0; i-- {
str += bitArr[i]
}
return str
}