Bird
0
0
DSA Cprogramming

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

Choose your learning style9 modes available
Mental Model
Every number in computers is stored in bits, and the last bit tells if a number is even or odd. If the last bit is 0, the number is even; if 1, it is odd.
Analogy: Think of a row of light switches representing bits. The last switch controls whether the number is even or odd. If the last switch is off (0), the number is even; if on (1), the number is odd.
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: Perform bitwise AND of number 5 with 1
5 in bits: 0101
1 in bits:  0001
AND result:  0001
Why: AND with 1 isolates the last bit to check if it is 0 or 1
Step 2: Check if AND result is 0 or 1
AND 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 C
#include <stdio.h>

// Function to check even or odd using bitwise AND
const char* checkEvenOdd(int num) {
    if ((num & 1) == 0) {
        return "Even";
    } else {
        return "Odd";
    }
}

int main() {
    int number = 5;
    printf("%d is %s\n", number, checkEvenOdd(number));
    return 0;
}
if ((num & 1) == 0) {
Check last bit by ANDing with 1 to determine 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 AND is a single operation regardless of number size
Space: O(1) because no extra memory is used besides input and output
vs Alternative: Compared to using modulo (%) operator which also runs in O(1), bitwise AND is often faster and more direct at hardware level
Edge Cases
number = 0
Returns Even because 0's last bit is 0
DSA C
if ((num & 1) == 0) {
number = -2
Returns Even because bitwise AND checks last bit regardless of sign
DSA C
if ((num & 1) == 0) {
number = 1
Returns Odd because last bit is 1
DSA C
if ((num & 1) == 0) {
When to Use This Pattern
When you need to quickly check if a number is even or odd without division, use bitwise AND with 1 because it directly inspects the last bit.
Common Mistakes
Mistake: Using modulo operator (%) instead of bitwise AND for checking even/odd
Fix: Use (num & 1) == 0 for faster and simpler check
Mistake: Checking if (num & 1) == 1 to decide even, which is reversed
Fix: Remember (num & 1) == 0 means even, else odd
Summary
Checks if a number is even or odd by looking at its last bit using bitwise AND.
Use when you want a fast, simple way to test evenness without division or modulo.
The last bit of a number tells if it is even (0) or odd (1).