Concept Flow - Check if Number is Even or Odd Using Bits
Start with number n
Perform bitwise AND: n & 1
Check result
End
We take the number, check its last bit using bitwise AND with 1. If result is 0, number is even; if 1, number is odd.
int n = 5; int result = n & 1; if (result == 0) Console.WriteLine("Even"); else Console.WriteLine("Odd");
| Step | Operation | Value of n | Bitwise AND (n & 1) | Result Interpretation | Output |
|---|---|---|---|---|---|
| 1 | Start with n | 5 (binary 0101) | |||
| 2 | Calculate n & 1 | 5 (0101) | 1 (0001) | 1 means odd | |
| 3 | Check if result == 0 | 5 | 1 | False | |
| 4 | Print output | 5 | 1 | Odd | Odd |
| 5 | End | 5 | 1 |
| Variable | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| n | 5 | 5 | 5 | 5 |
| result | undefined | 1 | 1 | 1 |
Check if number is even or odd using bitwise AND: - Use 'n & 1' to get last bit - If result is 0, number is even - If result is 1, number is odd - Faster than modulo operator - Works because binary last bit shows parity
num is odd using bits?int num = 14;
if ((num & 1) == 0)
Console.WriteLine("Even");
else
Console.WriteLine("Odd");int num = 7;
if (num & 1 == 1)
Console.WriteLine("Odd");
else
Console.WriteLine("Even");public string CheckEvenOdd(int num) {
// Options:
// A) return (num & 1) == 0 ? "Even" : "Odd";
// B) return (num | 1) == 0 ? "Even" : "Odd";
// C) return (num ^ 1) == 0 ? "Even" : "Odd";
// D) return (~num & 1) == 0 ? "Even" : "Odd";
}Pass the test and this pattern moves unknown