Leetcode 405. Convert a Number to Hexadecimal
You need to write a function that converts a given integer to its hexadecimal representation. For the purpose of this problem, assume that all integers are signed 32-bit integers, and you are not allowed to use any built-in libraries to directly solve this problem.
num
is 0, simply return “0”.x
is calculated by 2^32 + x
.Here is the implementation of the solution:
public class Solution {
public String toHex(int num) {
if (num == 0) {
return "0";
}
char[] hexChars = "0123456789abcdef".toCharArray();
StringBuilder hexString = new StringBuilder();
// we are only interested in the last 32 bits of num
while (num != 0 && hexString.length() < 8) {
int currentHexDigit = num & 0xf; // Extract the last 4 bits
hexString.append(hexChars[currentHexDigit]);
num >>>= 4; // Logical right shift by 4 bits
}
return hexString.reverse().toString();
}
public static void main(String[] args) {
Solution sol = new Solution();
// Test cases
System.out.println(sol.toHex(26)); // Expected "1a"
System.out.println(sol.toHex(-1)); // Expected "ffffffff"
}
}
num
is 0 and return “0” immediately.num & 0xf
.StringBuilder
.>>>
) to remove the last 4 bits.StringBuilder
contents are reversed at the end because we constructed the hex string from least significant to most significant digit.The time complexity of this conversion is O(1), because the loop iterates at most 8 times (since a 32-bit number can be represented by at most 8 hexadecimal digits). Thus, the computation does not depend on the size or value of the input integer.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?