Opening the reading…
Opening the reading…
BIT MANIPULATION › BASIC BIT CONCEPTS
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →The complement flips every bit that appears in num's binary representation, but it does not flip leading zeros. For example, 5 is written as 101, so its complement is 010, which is 2. The answer therefore needs one decision for each significant bit, not for every bit in the integer type.
A mask made of ones over exactly the same width solves this directly. XOR keeps a bit when the mask has 0 and flips it when the mask has 1, so XORing num with a same-width all-ones mask flips every relevant bit and nothing else. You can construct that mask by starting at 1 and repeatedly appending another 1 until it reaches num's highest set bit.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(b) | Each loop iteration adds one bit to mask, and mask grows from one bit to b bits. No bit is revisited after it has been added, so the loop performs exactly b - 1 iterations in the nontrivial case. |
| Space | O(1) | Only the integer mask is extra working storage; the output is a single integer and is not counted as extra space. The bound stays constant even for the largest allowed num, although the loop takes its worst-case number of iterations when num has 31 bits. |
#include <cstdint>
using namespace std;
class Solution {
public:
int findComplement(int num) {
int mask = 1;
while (mask < num) {
mask = (mask << 1) | 1;
}
return mask ^ num;
}
};The update mask = (mask << 1) | 1 performs two operations in the required order. The left shift makes room for one new bit, and the OR sets that new bit to one. The condition mask < num is also important: for num = 5, the mask sequence is 1, 3, 7, and 7 is the first value wide enough to cover 101. XORing 7 and 5 gives 2.