Bitwise Basics for Competitive Programming (Beginner Friendly)

Правка en1, от testUser44, 2025-10-10 19:34:38

Bitwise operations are very powerful tools in competitive programming. They work directly on the binary form of numbers and are extremely fast. Here are some simple but useful tricks every beginner should know.


1. Even or Odd Check – (n & 1)

Every number in binary ends with either 0 or 1. If the last bit is 1, the number is odd. If the last bit is 0, the number is even.

int n = 7;
if (n & 1) cout << "Odd\n";
else cout << "Even\n";

Explanation: Binary of 7 is 111. The last bit is 1, so it is odd. Binary of 8 is 1000. The last bit is 0, so it is even.


2. Divide by 2 – (n >> 1)

The right shift operator >> divides a number by 2 for each shift.

int n = 10;
cout << (n >> 1) << endl; // Output: 5

Explanation: 10 (1010 in binary) becomes 101 after one right shift, which equals 5.


3. Multiply by 2 – (n << 1)

The left shift operator << multiplies a number by 2 for each shift.

int n = 5;
cout << (n << 1) << endl; // Output: 10

Explanation: 5 (0101 in binary) becomes 1010 after one left shift, which equals 10.


4. Uppercase to Lowercase and Vice Versa

Characters are also stored as numbers (ASCII codes). In ASCII:

  • Uppercase letters 'A''Z' have the 5th bit unset (0).
  • Lowercase letters 'a''z' have the 5th bit set (1).

This allows easy conversion using bitwise operations.

Convert Uppercase to Lowercase

Set the 5th bit.

char A = 'A';
char a = A | (1 << 5);
cout << a << endl; // prints 'a'

Convert Lowercase to Uppercase

Unset the 5th bit.

char d = 'd';
char D = d & ~(1 << 5);
cout << D << endl; // prints 'D'

You can also use shorter tricks:

cout << (char)('C' | ' ') << endl; // 'C' -> 'c'
cout << (char)('c' & '_') << endl; // 'c' -> 'C'

5. Clearing Bits (LSB and MSB)

Sometimes we need to clear some bits (set them to zero).

Clear the lowest k bits (LSB)

int n = 255; // 11111111 in binary
int k = 3;
int result = n & ~((1 << (k + 1)) - 1);
// Clears bits 0,1,2,3
cout << result << endl;

Keep only the lowest k bits (clear MSB)

int n = 255; // 11111111
int k = 3;
int result = n & ((1 << (k + 1)) - 1);
// Keeps bits 0,1,2,3 -> 00001111
cout << result << endl; // 15

Summary

  1. Even or Odd Check: (n & 1)
  2. Divide by 2: (n >> 1)
  3. Multiply by 2: (n << 1)
  4. Uppercase ↔ Lowercase: set or unset the 5th bit
  5. Clear bits: use bit masks with ~ and shifts

Bitwise operations may look tricky at first, but they are fast, compact, and very helpful in contests once you understand the binary logic behind them.

Теги bitwise

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en1 Английский testUser44 2025-10-10 19:34:38 2933 Initial revision (published)