Loading
Leetcode / 405. Convert a Number To Hexadecimal

Pick a programming language:

Here is the source code for the solution to this problem.

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

        StringBuilder sb = new StringBuilder();
        int n = num;

        while (n != 0) {
            // Get the last 4 bits
            int bits = n & 0xf; // or 0b1111 or 15
            // UNSIGNED Shift for next iteration
            n = n >>> 4;

            char c;
            if (bits > 9) {
                // 10 becomes 'a', 11 becomes 'b', etc.
                c = (char) ('a' + (bits - 10));
            }
            else {
                c = Character.forDigit(bits, 10);
            }

            sb.append(c);
        }
        return sb.reverse().toString();
    }
}
Did you like the lesson? 😆👍
Consider a donation to support our work: