Checking if the i-th Bit is Set

Check if i-th bit is set using shift operators.

bool isBitSet(int n, int i) {
        return (n & (1 << i)) != 0;
        //OR
        return (n >> i) & 1;
}

Setting the i-th Bit

Set i-th bit to 1 using OR operator.

int setBit(int n, int i) {
        return n | (1 << i);
}

Clearing the i-th Bit

Clear i-th bit using AND operator.

int clearBit(int n, int i) {
        return n & ~(1 << i);
}

Toggling the i-th Bit

Toggle i-th bit using XOR operator.

int toggleBit(int n, int i) {
        return n ^ (1 << i);
}

Removing the Last Set Bit

Remove rightmost set bit using AND operator.

int removeLastSetBit(int n) {
        return n & (n - 1);
}

Checking if a Number is Power of 2

bool isPowerOfTwo(int n) {
        return (n > 0) && ((n & (n - 1)) == 0);
}

Counting Set Bits

Basic Approach