๐Ÿ“… Date: Feb 2, 2026
๐Ÿ”ฅ Topic: Set/Clear Bits, Power of 2 & Fast Exponentiation


๐ŸŽญ The Art of Masking

To change specific bits without affecting others, we use a "Mask". A mask is usually 1 << i (pushing a 1 to the position we want).

1️⃣ Set ith Bit (Make it 1)

Use OR ( | ) operator.
n | (1 << i)

2️⃣ Clear ith Bit (Make it 0)

Use AND ( & ) with NOT ( ~ ).
n & ~(1 << i)


⚡ Trick 3: Check Power of 2

Numbers like 2, 4, 8, 16 have only one bit set in binary.
Example: 8 is 1000, 7 is 0111.
Notice that 8 & 7 is 0.

Formula: if (n & (n-1) == 0) then it is a Power of 2.


๐Ÿš€ Fast Exponentiation (O(log n))

Calculating a^n normally takes O(n) time. But using bits, we can do it in O(log n).
We iterate through the bits of the power `n`. If the bit is 1, we multiply the answer with the base.


๐Ÿ’ป Day 32 Code: The Toolbox

#include <iostream>
using namespace std;

int main() {
    int n = 10; // Binary: 1010
    int i = 2;  // Target 2nd bit

    // 1. Set Bit
    int setRes = n | (1 << i);
    cout << "Setting 2nd bit of 10: " << setRes << endl; // 14 (1110)

    // 2. Clear Bit
    int clearRes = n & ~(1 << 1); // Clearing 1st bit
    cout << "Clearing 1st bit of 10: " << clearRes << endl; // 8 (1000)

    // 3. Power of 2 Check
    int p = 16;
    if ((p & (p - 1)) == 0)
        cout << p << " is a Power of 2!" << endl;

    // 4. Count Set Bits (Built-in function)
    cout << "Number of 1s in 10: " << __builtin_popcount(n) << endl;

    return 0;
}

๐Ÿ’ญ Thoughts

The n & (n-1) trick is legendary. I also touched upon Fast Exponentiation, which is crucial for large number calculations in cryptography.