Convert a Number to Hexadecimal

Given a 32-bit 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"

 

Constraints:

  • -231 <= num <= 231 - 1

My Solution

We can solve this problem by ANDing the number by 0xF at each iteration and adding the hex value of that nibble to a StringBuilder. If the nibble is greater than 10, we add the corresponding character. We have 8 iterations because it is a 32 bit number. Finally we remove leading zeros and reverse the output and return.

Time complexity would be O(1) because we just have 8 iterations which is a constant. Space complexity would also be O(1) because we hold a maximum of 8 characters for the output.

class Solution {
    public String toHex(int num) {
        if (num == 0) {
            return "0";
        }

        StringBuilder sb = new StringBuilder();
        int shifts = 8;

        for (int i = 0; i < shifts; i++) {
            int nibble = num & (0xF);
            if (nibble >= 10) {
                sb.append((char)('a' + (nibble - 10)));
            }
            else {
                sb.append(nibble);
            }

            num >>= 4;
        }

        int i = 7;
        while (sb.charAt(i) == '0') {
            sb.deleteCharAt(i);
            i--;
        }

        return sb.reverse().toString();
    }
}
Previous
Previous

Longest Palindrome

Next
Next

Sum of Left Leaves