Data Structures & Algorithms Bit Manipulation
💡
Exercise 152

Bit Manipulation Basics 10 XP Easy

Ctrl+Enter Run Ctrl+S Save

Welcome to Bit Manipulation — working directly with the 1s and 0s that computers actually use! 🔢

💡 Think of it like this: Computers store everything as binary (base 2). The number 5 in binary is 101, and 3 is 011. Bit manipulation lets us do super-fast operations on these binary digits.

# Binary representations: # Decimal → Binary # 0 → 0000 # 1 → 0001 # 2 → 0010 # 3 → 0011 # 5 → 0101 # 7 → 0111 # 8 → 1000 # 10 → 1010

Essential bit operations:

  • & AND — both bits must be 1: 5 & 3 = 101 & 011 = 001 = 1
  • | OR — at least one bit is 1: 5 | 3 = 101 | 011 = 111 = 7
  • ^ XOR — bits must be different: 5 ^ 3 = 101 ^ 011 = 110 = 6
  • ~ NOT — flip all bits: ~5 = -6
  • << Left shift — multiply by 2: 3 << 1 = 6
  • >> Right shift — divide by 2: 6 >> 1 = 3

🌟 XOR Magic: XOR has a special property — a ^ a = 0 and a ^ 0 = a. This is the key to many bit problems!

# XOR cancels out duplicates: 5 ^ 5 # = 0 (same number XORs to 0) 5 ^ 0 # = 5 (XOR with 0 gives back the number) 3 ^ 5 ^ 3 # = 5 (the 3s cancel out, leaving 5!)
📋 Instructions
Print the results of: 5 AND 3, 5 OR 3, 5 XOR 3, XOR of [4,1,2,1,2]
Use &, |, ^. For the array XOR, XOR all elements together — duplicates cancel out.
🧪 Test Cases
Input
5 & 3
Expected
1
Test case 1
Input
5 | 3
Expected
7
Test case 2
Input
5 ^ 3
Expected
6
Test case 3
Input
result
Expected
4
Test case 4
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.