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 →Bit position i is 1-based, but a shift count is 0-based. Therefore the bit at position i is reached by shifting 1 left by i - 1 places. This creates a mask with exactly one 1: the target bit is 1 in the mask, and every other bit is 0.
Once the mask exists, each operation follows from what AND and OR preserve. AND with the mask leaves the target bit isolated, OR with the mask forces the target bit to 1, and AND with the complemented mask forces the target bit to 0. The original num remains unchanged because every expression creates a result rather than modifying num.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(1) | The solution performs a fixed number of shifts, bitwise operations, and assignments, regardless of the numeric value of num or the selected position. |
| Space | O(1) extra | Only the mask and three scalar results are stored. The returned array is required output and is excluded from the extra-space bound. |
#include <vector>
using namespace std;
class Solution {
public:
vector<long long> bitManipulation(long long num, int i) {
long long mask = 1LL << (i - 1);
long long current = (num & mask) ? 1LL : 0LL;
long long setValue = num | mask;
long long clearValue = num & ~mask;
return vector<long long>{current, setValue, clearValue};
}
};The expression 1LL is important before the shift: it makes the mask a 64-bit value from the start. The ternary expression is also intentional. num & mask tells you whether the bit is present, but when the bit is set it returns the mask itself, such as 4 for position 3; the required first answer is 1, so the expression converts any nonzero result to 1.