0% found this document useful (0 votes)
5 views2 pages

C/C++ Bit Manipulation Techniques

The document provides C/C++ programming solutions for various bit manipulation problems. It includes methods to find the first set bit, toggle bits between specified positions, check if a number is a power of two, and count non-identical bits. Each solution is accompanied by code snippets and explanations of the logic used.

Uploaded by

yatharthst616
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

C/C++ Bit Manipulation Techniques

The document provides C/C++ programming solutions for various bit manipulation problems. It includes methods to find the first set bit, toggle bits between specified positions, check if a number is a power of two, and count non-identical bits. Each solution is accompanied by code snippets and explanations of the logic used.

Uploaded by

yatharthst616
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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)

You might also like