C/C++ Programming Questions
BIT Manipulation
1)Find the first set bit
Logic
While(n&1)==1;
Return count;
Else
N=n>>1;
Count++;
2)Toggle bits between l and r in a number
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int toggleBits(int n, int l, int r) {
// Create masks to toggle bits within the range [l, r]
int mask1 = ((1 << (r - l + 1)) - 1) << l; // Set bits from l to r
int mask2 = ((1 << (r - l + 1)) - 1); // Set bits from 0 to r-l
// Toggle the bits within the range [l, r] in n
return n ^ mask1 ^ mask2;
};
int main() {
int t;
cin >> t;
while (t--) {
int n, l, r;
cin >> n >> l >> r;
Solution ob;
cout << [Link](n, l, r) << endl;
return 0;
3)Power Of 2 using Bitwise operator
bool isPowerOfTwo(int n) {
// If n is less than or equal to 0, it can't be a power of two
if (n <= 0)
return false;
// A power of two has only one bit set in its binary representation.
// If we subtract 1 from a power of two, we get a number with all bits set to the right of the
original number's bit.
// For example, 8 (1000) - 1 = 7 (0111), 16 (10000) - 1 = 15 (01111), etc.
// If we perform bitwise AND between n and n - 1, it should result in 0 for a power of two.
// For example, 8 & 7 = 1000 & 0111 = 0000 (0), 16 & 15 = 10000 & 01111 = 0, etc.
return (n & (n - 1)) == 0;
4)Flip Non identical Bits
while (n) {
n = n & (n - 1); // Clear the rightmost set bit
count++; // Increment count for each set bit cleared
}
5)