Advertisement
Fastrail08

Bits Trick

May 27th, 2025
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. ✅ 2. Useful Bitwise Tricks (Common in CP & DP)
  2. 📌 A. Set / Check / Clear a specific bit
  3. cpp
  4. Copy
  5. Edit
  6. int x = 5; // 0101 in binary
  7.  
  8. // Set 2nd bit (0-indexed)
  9. x |= (1 << 2); // x becomes 0101 | 0100 = 1101 (13)
  10.  
  11. // Check if 3rd bit is set
  12. bool isSet = x & (1 << 3); // true if bit 3 is set
  13.  
  14. // Clear 0th bit
  15. x &= ~(1 << 0); // 1101 & ~(0001) = 1100 (12)
  16. 📌 B. Count number of set bits (popcount)
  17. cpp
  18. Copy
  19. Edit
  20. int x = 29; // Binary: 11101
  21. int count = __builtin_popcount(x); // count = 4 (set bits)
  22. 🚀 Useful for DP on subsets (e.g., TSP, bitmask problems)
  23.  
  24. 📌 C. Iterate all subsets of a bitmask
  25. cpp
  26. Copy
  27. Edit
  28. int mask = 0b1011; // Subsets of 4-element set {0,1,3}
  29. for (int sub = mask; sub > 0; sub = (sub - 1) & mask) {
  30. // sub is a subset of mask
  31. }
  32. 📌 D. Toggle a bit
  33. cpp
  34. Copy
  35. Edit
  36. int x = 6; // 0110
  37. x ^= (1 << 1); // Toggle 1st bit: 0110 → 0100 (4)
  38. 📌 E. Check if a number is a power of 2
  39. cpp
  40. Copy
  41. Edit
  42. bool isPow2 = (x > 0) && ((x & (x - 1)) == 0);
  43. 📌 F. Lowest set bit
  44. cpp
  45. Copy
  46. Edit
  47. int x = 12; // 1100
  48. int lowBit = x & -x; // Gets 3rd bit (value 4)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement