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"
这道题不难,解法一比较直观,解法二算是一个改进,主要通过hash巧妙地避开了转换函数numToString
- num /= 16 可以写成 num >>= 4, 移位更具有效率
- 固定的16进制转换等,最好用函数数组来快速转换m[num%16]
- 负数变正数的方法:
- num += (1 << 32)
- num += -1&0xffffffff + 1
// 解法一
func numToString(n int) string { if n < 0 || n > 15 { return "" }
if n < 10 {
return string(byte('0' + n))
}
return string(byte(n - 10 + 'a'))
}
func toHex(num int) string { if num == 0 { return "0" }
if num < 0 {
num += -1&0xffffffff + 1
}
ret := ""
for num != 0 {
ret = numToString(num%16) + ret
num >>= 4 // num /= 16 位移更有效率
}
return ret
}
// 解法二
func toHex2(num int) (answer string) { m := []byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'} if num == 0 { return "0" } if num < 0 { num = (1 << 32) + num } for num > 0 { answer = string(m[num%16]) + answer num >>= 4 } return answer }