Given an integer num
, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used.
Constraints:
-2^31 <= num <= 2^31 - 1
num
is 0
?
"0"
should be returned.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))
"0"
if the number is zero.2^32
(since we’re dealing with 32-bit integers)."0123456789abcdef"
to construct the resultant string.
num % 16
.num
by dividing it by 16
.O(log N)
, where N
is the absolute value of the input number. This is because we’re dividing the number by 16
repeatedly, which reduces the number of operations proportional to the logarithm base 16.O(log N)
as well due to the list used for storing the hexadecimal digits.This approach ensures that the solution is efficient and handles all edge cases, including negative numbers and zero.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?