题目地址
https://leetcode.com/problems/convert-a-number-to-hexadecimal/
题目描述
405. Convert a Number to Hexadecimal
Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used.
All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.
Note: You are not allowed to use any built-in library method to directly solve this problem.
Example 1:
Input: num = 26
Output: "1a"
Example 2:
Input: num = -1
Output: "ffffffff"
思路
- 每次与0x0F与操作. 得到的值查表.
- 相当于每次num的最低位被转换成十六进制.
- 之后无符号右移4位.
- 如此往复.
关键点
- 注意, 从最低位开始转换, 因此注意输出顺序.
代码
- 语言支持:Java
class Solution {
public String toHex(int num) {
if (num == 0) {
return "0";
}
StringBuffer sb = new StringBuffer();
char[] map = "0123456789abcdef".toCharArray();
while (num != 0) {
int index = num & (0x0f);
sb.append(map[index]);
num >>>= 4;
}
return sb.reverse().toString();
}
}
网友评论