405. Convert a Number to Hexadecimal
1. Question
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.
2. Examples
Example 1:
Input: num = 26
Output: "1a"
Example 2:
Input: num = -1
Output: "ffffffff"
3. Constraints
- -231 <= num <= 231 - 1
4. References
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/convert-a-number-to-hexadecimal 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
5. Solutions
class Solution {
public String toHex(int num) {
if (num == 0) {
return "0";
}
final char[] ch = "0123456789abcdef".toCharArray();
StringBuilder sb = new StringBuilder();
while (num != 0) {
int index = num & 15;
sb.append(ch[index]);
num >>>= 4;
}
return sb.reverse().toString();
}
}