Description
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; its complement is "010", which is the integer 2.
Given an integer num, return its complement.
Answer
class Solution:
def findComplement(self, num: int) -> int:
bit_len = num.bit_length()
mask = (1 << bit_len) - 1
return num ^ maskSolution
This problem is a bit manipulation that involves flipping the bits. Whenever this happens, the first thing that comes to mind should be XOR because the XOR logic is equivalent to even parity.
Then, all we need is a bitmask consisting of all 1βs that is the length of the binary representation of num. We can achieve this by shifting 1 to the left by the length of the binary representation of num then subtracting 1.
Once we have our bitmask, we can simply XOR with our original number and return the result.