Solving Leetcode Interviews in Seconds with AI: Convert a Number to Hexadecimal
Introduction
In this blog post, we will explore how to solve the LeetCode problem "405" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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
Explanation
Here's an efficient solution to convert a 32-bit integer to its hexadecimal representation, adhering to the given constraints.
- Bit Masking: Use bitwise AND operations to extract 4 bits at a time from the integer. Each 4-bit segment represents a hexadecimal digit.
- Iteration and Conversion: Iterate through the 32 bits of the integer (8 hex digits). Convert each 4-bit value to its corresponding hexadecimal character (0-9, a-f).
Handle Leading Zeros: Remove leading zeros from the resulting string, but ensure that "0" is returned if the original number is 0.
Runtime Complexity: O(1), because the loop iterates a fixed number of times (8 times for 32 bits). Storage Complexity: O(1), since the string length is bounded by the number of hexadecimal digits (at most 8).
Code
def toHex(num: int) -> str:
"""
Converts a 32-bit integer to its hexadecimal representation.
"""
if num == 0:
return "0"
hex_chars = "0123456789abcdef"
result = ""
for _ in range(8):
digit = num & 0xF # Extract the last 4 bits
result = hex_chars[digit] + result # Prepend the hex character
num >>= 4 # Right-shift by 4 bits
# Remove leading zeros
while result.startswith("0") and len(result) > 1:
result = result[1:]
return result