𝙎𝙤𝙢𝙚 𝙐𝙨𝙚𝙛𝙪𝙡 𝘽𝙞𝙩𝙈𝙖𝙨𝙩:

1) To Multiply/divide an integer by 2:

n*2 = (n<<1)
n/2 = (n>>1);

2) To set/turn on the i-th bit

n |= (1<<i)

3) To check i-th bit is set or not

If (n & (1<<i) == 0) => set
else not set

**4) To clear/turn off the i-th bit **

n &= ~(1<<i)

5) To toggle/flip the i-th bit

n ^= (1<<i)

6) To turn on all bits in a set of size sz

n = (1<<sz) - 1

eg, if sz=3 then n = 7 (base 10) = 111 (base 2)

7) To check n is odd/even

n & 1 == 1 // odd

n & 1 == 0 // even

8) To check if n if divisible by power of 2

n & ((1<<k) - 1) == 0 // n is divisible by 2^k (= (1<<k)).

9) To check if n is a power of 2

n && !(n & (n - 1)) == 1

**10) To get the value of the least significant bit of n that is on **

lsb = n & (-n)

eg, n = 10 = 1010 (base 2)

lsb = 2 = 0010 (base 2) = pow(2,j), where j=1

To get the actual j-th index use __builtin_ctz(lsb)

11) Some built-in bit manipulation functions:

__builtin_popcount(n) // return count of set bit in n

__builtin_ctz(n)               // return the count of tailing zero

eg, n = 8 = 1000 (base 2). Here tailing zero = 3  

Some Important Problems:

  1. Missing Number: https://leetcode.com/problems/missing-number/
  2. Bitwise ORs of Subarrays: https://leetcode.com/problems/bitwise-ors-of-subarrays/

3)XOR Queries of a Subarray: https://leetcode.com/problems/xor-queries-of-a-subarray/
4)Minimum Flips to Make a OR b Equal to c: https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/

  1. Count Triplets That Can Form Two Arrays of Equal XOR: https://leetcode.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/
  2. Bitwise AND of Numbers Range: https://leetcode.com/problems/bitwise-and-of-numbers-range/
  3. Decode XORed Permutation: https://leetcode.com/problems/decode-xored-permutation/
Comments (0)