1. Bit-by-Bit Linear Scan
Intuition
Loop through each bit position i from l to r. Construct a single-bit probe 1 << (i - 1). If (y & probe) != 0, then activate that bit in x by computing x |= probe.
When to apply: When simplicity and readability across a few bits are preferred.
Algorithm
- Step 1: Loop i from l to r.
- Step 2: Check if (y & (1 << (i - 1))) != 0.
- Step 3: If true, set bit in x: x |= (1 << (i - 1)).
- Step 4: Return x.
#include <iostream> using namespace std; int copySetBitsBrute(int x, int y, int l, int r) { for (int i = l; i <= r; ++i) { long long bitMask = 1LL << (i - 1); if ((y & bitMask) != 0) { x |= bitMask; } } return x;} int main() { cout << "Brute (44, 3, 1, 5): " << copySetBitsBrute(44, 3, 1, 5) << endl; // 47 cout << "Brute (16, 2, 1, 3): " << copySetBitsBrute(16, 2, 1, 3) << endl; // 18 return 0;}Time & Space Complexity
- Time complexity:
O(r - l + 1) - Space complexity:
O(1)