0
0
DSA Pythonprogramming

Check if Number is Even or Odd Using Bits in DSA Python

Choose your learning style9 modes available
Mental Model
Every number in computers is stored in bits. The last bit tells if a number is even or odd: 0 means even, 1 means odd.
Analogy: Think of a parking lot where cars park in spots numbered 0,1,2,... The last spot number's last digit tells if the spot is even or odd. Checking the last digit is quick and easy.
Number bits:  ... b3 b2 b1 b0
                  ↑
               last bit
Dry Run Walkthrough
Input: number = 5
Goal: Determine if 5 is even or odd using bit operations
Step 1: Take the last bit of 5 using bitwise AND with 1
5 in bits: 0101
1 in bits: 0001
5 & 1 = 0001 (which is 1)
Why: The last bit shows if the number is odd (1) or even (0)
Step 2: Check if result is 0 or 1
Result = 1
Why: If result is 1, number is odd; if 0, number is even
Result:
5 is odd because last bit is 1
Annotated Code
DSA Python
def is_even_or_odd(num: int) -> str:
    # Use bitwise AND to check last bit
    if (num & 1) == 0:
        return "Even"
    else:
        return "Odd"

# Driver code
number = 5
result = is_even_or_odd(number)
print(f"{number} is {result}")
if (num & 1) == 0:
Check last bit to decide even or odd
return "Even"
Return Even if last bit is 0
return "Odd"
Return Odd if last bit is 1
OutputSuccess
5 is Odd
Complexity Analysis
Time: O(1) because bitwise operations take constant time regardless of number size
Space: O(1) because no extra space is used
vs Alternative: Using modulo (%) operator also takes O(1) time but bitwise AND is faster and more direct
Edge Cases
number = 0
Returns Even because 0's last bit is 0
DSA Python
if (num & 1) == 0:
number = 1
Returns Odd because 1's last bit is 1
DSA Python
if (num & 1) == 0:
negative number, e.g., -3
Returns Odd because bitwise AND with 1 still checks last bit correctly
DSA Python
if (num & 1) == 0:
When to Use This Pattern
When you need to quickly check if a number is even or odd without division or modulo, use bitwise AND with 1 because it directly inspects the last bit.
Common Mistakes
Mistake: Using modulo operator (%) instead of bitwise AND when bitwise is required for performance or learning
Fix: Replace num % 2 with num & 1 to check last bit directly
Mistake: Checking if num & 1 equals 1 explicitly instead of checking if equals 0 for even
Fix: Use if (num & 1) == 0 for even, else odd for clarity
Summary
It checks the last bit of a number to decide if it is even or odd.
Use it when you want a fast, simple way to check even or odd without division.
The last bit of a binary number is 0 for even and 1 for odd numbers.