Bit Manipulation
Bit Manipulation
- Srivaths P
Goal:
• Understand bit manipulation and its use cases.
• Learn tips for bit manipulation.
• Learn brute-forcing using bitmasks.
• Find common patterns in bit manipulation problems.
Where is Bit Manipulation used?
Problems may or may not directly involve bit manipulation.
18 << 3 = 144
18 >> 3 = 2
Bitmasking
A bitmask is a sequence of 𝑁 bits that encodes a subset, where the
element is taken if a bit is set, and not taken if a bit is unset.
Ex: 10110 would mean indices 1, 2, 4 are taken, while 0, 3 are not.
• Bit-dependent problems:
Cannot solve for each bit separately. All the bits are interconnected
and cannot be treated as independent.
Problems:
• https://www.codechef.com/problems/BITEQU
• https://www.atcoder.jp/contests/abc289/tasks/abc289_c
• https://www.codechef.com/problems/LOSTARRAY_
• https://www.codechef.com/problems/MAXAND18
Some Properties
• OR/AND/XOR are associative and commutative.
• 𝐴^0 = 𝐴
• 𝐴^𝐴 = 0
• If 𝐴 ^ 𝐵 = 𝐶, then 𝐴 ^ 𝐶 = 𝐵
• 𝐴^𝐵^𝐵 = 𝐴
• 𝐴 & 𝐵 ≤ min(𝐴, 𝐵)
• 𝐴 | 𝐵 ≥ max(𝐴, 𝐵)
• (𝐴 | 𝐵) + (𝐴 & 𝐵) = 𝐴 + 𝐵
• (𝐴 & 1) is 1 if 𝐴 is odd, else 0
• 𝐴 & (𝐴 − 1) is 0 if 𝐴 is a power of 2 (except when 𝐴 = 0)
Resources
Number base:
https://brilliant.org/wiki/number-base/
Bit manipulation:
• https://codeforces.com/blog/entry/73490 (highly recommended)
• https://www.hackerearth.com/practice/basic-programming/bit-
manipulation/basics-of-bit-manipulation/tutorial/
Bitsets:
• https://www.youtube.com/watch?v=jqJ5s077OKo
Resources
More properties:
https://stackoverflow.com/questions/12764670/are-there-any-bitwise-operator-laws
https://medium.com/biffures/bits-101-120f75aeb75a
https://medium.com/biffures/part-2-the-beauty-of-bitwise-and-or-cdf1d8d87891
https://medium.com/biffures/part-3-or-and-20ccc9938f05
https://medium.com/biffures/part-4-bitwise-patterns-7b17dae3eee0