Bit Manipulation 2
Bit Manipulation 2
By Harsh Gupta
Goal
• Cool tips for bit manipulation.
• Brute-forcing using bitmasks.
• Understanding bitsets.
Some Cool Tricks
● Swap 2 numbers without a temporary variable
● 2^k - 1 has last k bits set
● builtin_popcount and builtin_popcountll
● builtin_clz / _ builtin_clzll
● builtin_ctz / _builtin_ctzll
Bitmasking
A bitmask is nothing but a sequence of bits where every bit represents
something.
Can you think of some better way which consumes less memory?
Instead of using an array of 30 boolean variables
We can use a sequence of 30 bits where
Defining bitset:
bitset<320> bit;
bit[i] can be used to access and set ith bit just like we use arr[i] to
access or set the ith element of an array
Bitsets (CONTD…)
In these problems, whether the current bit is set or not doesn’t affect
the other bits, so we can just solve for every bit individually.
Problem:
● XORwice
Bit Dependent Problems
Here the bits are interdependent, whether we set a bit or unset it can
affect other bits.
Example - Find the largest number less than 2^8 where at most 3 bits
are set.
Here the whether we can set a bit or not depends upon the other bits
as we cannot set more than 3 bits.
Problem: