Bits Manipulation
View on GitHubBit Manipulation
Introduction
Bit manipulation is a technique used to manipulate the bits that make up a binary number. In competitive programming, this technique can be used to solve problems quickly and efficiently. Here, I will introduce you to bit manipulation and how it can be used in competitive programming.
Basic Bitwise Operators
The following are the basic bitwise operators you need to know:
- AND (
&): The result ofa & bis a number where each bit is set to 1 only if the corresponding bits ofaandbare both 1. Otherwise, the bit is set to 0. - OR (
|): The result ofa | bis a number where each bit is set to 1 if either the corresponding bit ofaorbis 1. Otherwise, the bit is set to 0. - XOR (
^): The result ofa ^ bis a number where each bit is set to 1 if the corresponding bits ofaandbare different. Otherwise, the bit is set to 0. - NOT (
~): The result of~ais a number where each bit is the complement of the corresponding bit ina. That is, if the bit inais 0, the bit in the result is 1, and vice versa.
Bitwise Shift Operators
The following are the bitwise shift operators:
- Left Shift (
<<): The result ofa << bis a number where the bits ofaare shifted left bybpositions. The leftmostbbits are set to 0. - Right Shift (
>>): The result ofa >> bis a number where the bits ofaare shifted right bybpositions. The rightmostbbits are set to 0.
Bit Manipulation Techniques
Here are some common bit manipulation techniques you can use in competitive programming:
- Setting a bit: To set the
ith bit of a numbern, you can use the expressionn |= (1 << i). - Clearing a bit: To clear the
ith bit of a numbern, you can use the expressionn &= ~(1 << i). - Checking if a bit is set: To check if the
ith bit of a numbernis set, you can use the expressionn & (1 << i) != 0. - Counting the number of set bits in a number: To count the number of set bits in a number
n, you can use the following code snippet:
count = 0
while n:
count += n & 1
n >>= 1
Bit manipulation is a powerful technique that can be used to solve problems quickly and efficiently in competitive programming. By understanding the basic bitwise operators and bitwise shift operators, as well as common bit manipulation techniques, you will be able to solve problems that would otherwise be difficult or time-consuming to solve.
And we are here to learn it in practice and get benefit of using it.
Enjoy Bits Manipulation!
My Session @ ICPC SCU
Reading Materials
- Bitwise Operators in C/C++ (GeeksforGeeks)
- Bitwise Hacks for Competitive Programming (GeeksforGeeks)
- Bit Tricks for Competitive Programming (GeeksforGeeks)
- Bits Manipulation: Important Tactics (GeeksforGeeks)
- Bitwise Algorithms (GeeksforGeeks)
- Bit Magic Articles (GeeksforGeeks)
- How to use bit manipulation to solve problems easily and efficiently (LeetCode)