Loading

LeetCode problem#405

Convert a Number to Hexadecimal

Solved in 1 languageJava

Solve it on LeetCode(opens in a new tab)

Solution

29 lines
1class Solution {
2    public String toHex(int num) {
3        if (num == 0) {
4            return "0";
5        }
6
7        StringBuilder sb = new StringBuilder();
8        int n = num;
9
10        while (n != 0) {
11            // Get the last 4 bits
12            int bits = n & 0xf; // or 0b1111 or 15
13            // UNSIGNED Shift for next iteration
14            n = n >>> 4;
15
16            char c;
17            if (bits > 9) {
18                // 10 becomes 'a', 11 becomes 'b', etc.
19                c = (char) ('a' + (bits - 10));
20            }
21            else {
22                c = Character.forDigit(bits, 10);
23            }
24
25            sb.append(c);
26        }
27        return sb.reverse().toString();
28    }
29}

Want a walkthrough of this Java solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.