405. Convert a Number to Hexadecimal (Easy)
https://leetcode.com/problems/convert-a-number-to-hexadecimal/
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
0
s. 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"
Solutions
class Solution {
Map<Integer, String> map;
private void init() {
if (map != null) {
return;
}
map = new HashMap<>();
map.put(0, "0");
map.put(1, "1");
map.put(2, "2");
map.put(3, "3");
map.put(4, "4");
map.put(5, "5");
map.put(6, "6");
map.put(7, "7");
map.put(8, "8");
map.put(9, "9");
map.put(10, "a");
map.put(11, "b");
map.put(12, "c");
map.put(13, "d");
map.put(14, "e");
map.put(15, "f");
}
public String toHex(int num) {
init();
if (num == 0) {
return "0";
}
long numx = num;
if (num < 0) {
// Note that 2l must be long type and int doesn't work.
numx = (2l << 31) + num;
}
String ans = "";
while (numx != 0) {
long remainder = numx % 16;
ans = map.get((int) remainder) + ans;
numx = numx / 16;
}
return ans;
}
}