Understanding the Problem
We are given an integer n
, and our goal is to check whether this number is even or odd. Normally, this is done using the modulo operator (n % 2
), but in this case, we want to solve it using bitwise operations.
This approach is fast and memory-efficient because bitwise operations work directly at the binary level. The key insight here is:
- In binary, the least significant bit (LSB) of a number determines whether it's even or odd.
- If the LSB is
0
, the number is even.
- If the LSB is
1
, the number is odd.
We can extract the LSB using the bitwise AND operation: n & 1
.
Step-by-Step Solution with Example
step 1: Take an example number
Let's consider n = 10
. In binary, this is 1010
.
step 2: Perform bitwise AND with 1
We apply the operation: 10 & 1
.
Binary of 10 is 1010
Binary of 1 is 0001
Bitwise AND result: 0000
→ which is 0.
step 3: Interpret the result
Since the result is 0
, that means the least significant bit is 0 — so 10 is even.
step 4: Try another example
Now let's try n = 7
. In binary: 0111
7 & 1 = 0111 & 0001 = 0001
→ which is 1
So 7 is odd.
Edge Cases
- n = 0: Binary is
0000
. 0 & 1 = 0
→ even. Works fine.
- n = -3: Binary representation in 2's complement still preserves the LSB.
-3 & 1 = 1
→ odd. Also works correctly.
- Very large numbers: The bitwise operation is constant time (
O(1)
), so it's extremely fast regardless of how large the number is.
Final Thoughts
Using n & 1
to determine whether a number is even or odd is a smart and efficient trick rooted in binary logic. It's especially helpful in performance-critical applications like competitive programming or embedded systems where every CPU cycle counts.
Remember, this method works reliably for both positive and negative integers because the least significant bit always reflects parity, even in 2’s complement representation.
Comments
Loading comments...