Bit wise odd or even
Problem Link
Problem Statement
Given an integer n, determine whether it is even or odd.
Return:
-
trueif the number is even -
falseif the number is odd
Examples
Example 1:
Input: n = 1
Output: false
Explanation: 1 is odd.
Example 2:
Input: n = 2
Output: true
Explanation: 2 is even.
Constraints
0 <= n <= 10⁶
Intuition
In binary representation:
-
Even numbers always end with a
0as the least significant bit (LSB) -
Odd numbers always end with a
1as the LSB
So, we can check the parity of a number by checking if the LSB is set using a bitwise AND with 1.
Approach: Bitwise AND with 1
To check whether a number is even:
-
If
(n & 1) == 0→ Even -
Else → Odd
This is because:
-
& 1extracts the least significant bit -
That bit determines whether the number is odd or even
Java Code
class Solution {
static boolean isEven(int n) {
return (n & 1) == 0;
}
}
Time and Space Complexity
| Metric | Value |
|---|---|
| Time Complexity | O(1) |
| Space Complexity | O(1) |
| Explanation | Uses a single bitwise operation, no loops or extra space |
Dry Run
Input: n = 2
-
Binary of
2:10 -
(2 & 1)=10 & 01=00→0→ Even → Returnstrue
Input: n = 3
-
Binary of
3:11 -
(3 & 1)=11 & 01=01→1→ Odd → Returnsfalse
Conclusion
This problem is a basic yet powerful example of how bitwise operations can optimize simple checks like odd/even determination.
Using (n & 1) is faster than using % 2 and is widely used in low-level or performance-critical code.