algoadvance

Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used.

Constraints:

Clarifying Questions

  1. Q: Should the hexadecimal letters be in uppercase or lowercase?
    • A: The hexadecimal letters should be in lowercase.
  2. Q: How should we handle negative numbers?
    • A: We should use two’s complement for negative numbers, which involves a bit manipulation strategy.
  3. Q: What should be returned if num is 0?
    • A: The string "0" should be returned.

Code

def toHex(num):
    if num == 0:
        return "0"

    # handle negative numbers by adjusting for two's complement
    if num < 0:
        num += 2**32

    hex_chars = "0123456789abcdef"
    result = []

    while num > 0:
        result.append(hex_chars[num % 16])
        num //= 16

    return "".join(reversed(result))

Strategy

  1. Edge Case for Zero: Directly return "0" if the number is zero.
  2. Handling Negative Numbers: Convert the negative numbers to their two’s complement equivalent by adding 2^32 (since we’re dealing with 32-bit integers).
  3. Convert to Hexadecimal: Use hexadecimal characters "0123456789abcdef" to construct the resultant string.
    • Append the appropriate character by taking num % 16.
    • Reduce num by dividing it by 16.
    • Add characters to a list and reverse it at the end for correct order.

Time Complexity

This approach ensures that the solution is efficient and handles all edge cases, including negative numbers and zero.

Try our interview co-pilot at AlgoAdvance.com