Number Complement Problem
Description
LeetCode Problem 476.
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 < 2^31
Solution
Approach: XOR with an All-Ones Mask
Flipping a bit is the same as XOR-ing it with 1, and XOR-ing with 0 leaves it alone. So if mask has a 1 in every position that num uses and 0 everywhere above, the answer is simply num ^ mask.
Build the mask by starting from 1 and shifting in another 1 bit (mask = (mask << 1) | 1) while mask < num. This gives 1, 3, 7, 15, ..., and the loop stops at the first value 2k − 1 that is at least num, which is exactly the mask covering the k bits of num.
For num = 5 (101): the mask grows 1 → 3 → 7, and 101 ^ 111 = 010, which is 2.
The detail to get right is that ~num alone is not the answer: it also flips the leading zeros above the highest set bit, giving a negative number. The mask limits the flip to the bits num actually has. The mask never exceeds 231 − 1, so it fits in a 32-bit integer.
Complexity: O(log num) time, one step per bit of num, and O(1) space.
class Solution:
def findComplement(self, num: int) -> int:
# Smallest number of the form 0b111...1 that covers every bit of num.
mask = 1
while mask < num:
mask = (mask << 1) | 1
return num ^ mask # flip exactly those bits
Now write it from memory
Close the write-up and solve it yourself against the tests.