Skip to content

405. Convert a Number to Hexadecimal

Description

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

Solutions

Solution 1

Thinking

A \(32\)-bit two's-complement integer must be printed in hex, including negatives. Digit-by-digit decimal conversion fights the sign; grouping \(4\) bits does not.

Eight groups from high to low, each masked with \(0\text{xF}\), map through a digit table. Skip leading zeros until a nonzero nibble appears; treat \(0\) as a special case.

Scanning from the high end lets us drop leading zeros without reversing a buffer.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
    def toHex(self, num: int) -> str:
        if num == 0:
            return '0'
        chars = '0123456789abcdef'
        s = []
        for i in range(7, -1, -1):
            x = (num >> (4 * i)) & 0xF
            if s or x != 0:
                s.append(chars[x])
        return ''.join(s)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
    public String toHex(int num) {
        if (num == 0) {
            return "0";
        }
        StringBuilder sb = new StringBuilder();
        while (num != 0) {
            int x = num & 15;
            if (x < 10) {
                sb.append(x);
            } else {
                sb.append((char) (x - 10 + 'a'));
            }
            num >>>= 4;
        }
        return sb.reverse().toString();
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
public:
    string toHex(int num) {
        if (num == 0) return "0";
        string s = "";
        for (int i = 7; i >= 0; --i) {
            int x = (num >> (4 * i)) & 0xf;
            if (s.size() > 0 || x != 0) {
                char c = x < 10 ? (char) (x + '0') : (char) (x - 10 + 'a');
                s += c;
            }
        }
        return s;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
func toHex(num int) string {
    if num == 0 {
        return "0"
    }
    sb := &strings.Builder{}
    for i := 7; i >= 0; i-- {
        x := num >> (4 * i) & 0xf
        if x > 0 || sb.Len() > 0 {
            var c byte
            if x < 10 {
                c = '0' + byte(x)
            } else {
                c = 'a' + byte(x-10)
            }
            sb.WriteByte(c)
        }
    }
    return sb.String()
}

Solution 2

Thinking

Solution 1 already walks \(4\)-bit groups. Solution 2 builds the same digits with arithmetic instead of a lookup table.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
    public String toHex(int num) {
        if (num == 0) {
            return "0";
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 7; i >= 0; --i) {
            int x = (num >> (4 * i)) & 0xf;
            if (sb.length() > 0 || x != 0) {
                char c = x < 10 ? (char) (x + '0') : (char) (x - 10 + 'a');
                sb.append(c);
            }
        }
        return sb.toString();
    }
}

Comments