Problem Description
Given an integer n, return its complement. The complement of an integer is obtained by flipping all bits in its binary representation (changing 0s to 1s and 1s to 0s).
Key Insights
- Convert the integer to its binary form.
- Determine a mask that covers all bits in n (mask will have all bits set to 1 for the length of n in binary).
- Use the XOR operation between n and the mask to flip the bits.
- Handle the edge case when n equals 0.
Space and Time Complexity
Time Complexity: O(1) (the number of iterations is bounded by the number of bits of n) Space Complexity: O(1)
Solution
The approach starts by creating a mask that has all bits set to 1 corresponding to the bit-length of n. This is done by continuously left shifting a mask starting from 1 until it exceeds n, then subtracting 1 to fill in all lower bits with 1s. Finally, an XOR of n with this mask flips the bits of n, resulting in its complement.