↓Skip to main content
  1. LeetCode/

LeetCode 405: Convert a Number to Hexadecimal

·2 mins· ·
LeetCode Easy Math String Bit-Manipulation
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-23

  • Submissions: Runtime Error ×2 → Wrong Answer ×2 → Accepted

Approach
#

Each hex digit is 4 bits (Bit Manipulation; also base conversion from Math Template 7). Negatives use 32-bit two’s complement, and num & 0xffffffff (adding 2^32) gives the matching non-negative value. Then repeatedly look up num & 15 and shift num >>= 4 until 0. For num = 0 the loop never runs, so return "0".

My Attempts
#

  • Attempt 1 looped while num > 15, dropping the last digit, and returned an empty string for num = 0.
  • After adding the 0 case, negatives were unhandled: -9 returned an empty string instead of "fffffff7". Adding num += 2**32 passed.

Solution
#

class Solution:
    def toHex(self, num: int) -> str:
        if num == 0:
            return "0"
        num &= 0xFFFFFFFF
        digits = "0123456789abcdef"
        res = []
        while num:
            res.append(digits[num & 15])
            num >>= 4
        return "".join(reversed(res))

Complexity
#

Time O(8), space O(1).

Mistakes to Avoid
#

  • Convert negatives to 32-bit two’s complement first.
  • Loop while num > 0; num > 15 drops the last digit.
  • 0 returns "0".

Interview Explanation
#

I AND negatives with 0xffffffff to get the two’s-complement value, then repeatedly map the lowest 4 bits and shift by 4, reversing at the end; 0 returns directly. At most 8 digits.

Related

LeetCode 67: Add Binary
·2 mins
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 note: add from the ends of both strings digit by digit, with carry sum // 2 and digit sum % 2
LeetCode 342: Power of Four
·1 min
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 342 note: confirm a power of two, then that the single 1 sits at an even position: n & 0x55555555 != 0, or n % 3 == 1
LeetCode 389: Find the Difference
·1 min
LeetCode Easy Hash-Table String Bit-Manipulation Sorting
LeetCode 389 note: t has one extra character; XOR every character of both strings, pairs cancel, and the extra one remains
LeetCode 412: Fizz Buzz
·1 min
LeetCode Easy Math String Simulation
LeetCode 412 note: check multiples of 15 first, then 5 and 3; multiples need %, not //
LeetCode 231: Power of Two
·2 mins
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 231 note: a power of two has exactly one set bit, and n & (n - 1) clears the lowest one, so the result is 0 exactly then; n must be positive
LeetCode 171: Excel Sheet Column Number
·1 min
LeetCode Easy Math String
LeetCode 171 note: scan left to right with res = res × 26 + letter value (A = 1)