Solving Leetcode Interviews in Seconds with AI: Number Complement
Introduction
In this blog post, we will explore how to solve the LeetCode problem "476" 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
The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation. For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2. Given an integer num, return its complement. Example 1: Input: num = 5 Output: 2 Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. Example 2: Input: num = 1 Output: 0 Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. Constraints: 1 <= num < 231 Note: This question is the same as 1009: https://leetcode.com/problems/complement-of-base-10-integer/
Explanation
Here's a breakdown of the solution:
- Find the Mask: Determine the smallest power of 2 that's greater than or equal to
num. We'll use this to create a mask of all 1s in binary that has the same number of digits asnum's binary representation. - Create the Mask: Subtracting 1 from that power of 2 gives us a mask with the appropriate number of 1s. For example, if
numis 5 (binary 101), the power of 2 is 8 (binary 1000). Subtracting 1 gives us 7 (binary 0111). XOR Operation: Perform an XOR operation between
numand the mask. This flips the bits, giving us the complement.Time & Space Complexity: O(1) time complexity, O(1) space complexity
Code
class Solution:
def bitwiseComplement(self, num: int) -> int:
if num == 0:
return 1
# Find the number of bits required to represent num
num_bits = 0
temp = num
while temp > 0:
temp >>= 1
num_bits += 1
# Create a mask with all 1s having the same number of bits as num
mask = (1 << num_bits) - 1
# XOR num with the mask to flip the bits
return num ^ mask