Check if Number is Even or Not
Problem Statement:β
Given a positive integerΒ n, determine whether it is odd or even. ReturnΒ trueΒ if the number is even andΒ falseΒ if the number is odd.
-
Example:
Examples:
Input: n = 15
Output:false
Explanation:The number is not divisible by 2, Odd number.Input: n = 44
Output:true
Explanation:The number is divisible by 2, Even number.
β Solution: Bit Manipulationβ
class Solution {
public:
bool isEven(int n) {
// If the least significant bit is 1, the number is odd
// If it's 0, the number is even
return !(n & 1);
}
};
π How It Worksβ
- Every even number has 0 as its least significant bit (LSB).
(n & 1)checks the LSB:- If
n & 1is1, then the number is odd. - If
n & 1is0, then the number is even.
- If
- We use
!to negate the result, so:!(n & 1)returnstruefor even numbers,falsefor odd numbers.
Example:
n = 6 -> binary: 0110 β LSB = 0 β even β return true
n = 7 -> binary: 0111 β LSB = 1 β odd β return false
π§© Key Formulaβ
!(n & 1)
This uses bitwise AND with 1 to check the parity.
β±οΈ Time & Space Complexityβ
| Complexity | Value |
|---|---|
| Time | O(1) |
| Space | O(1) |
β οΈ Edge Casesβ
- Negative numbers are correctly handled by bitwise operations in C++.
- Zero is considered even (since LSB is 0).
π‘ Other Approachesβ
| Approach | Example | Description |
|---|---|---|
| Modulo | n % 2 == 0 | Simple and readable, but slightly slower due to division |
| Bitmasking | !(n & 1) β
| Fast and efficient using LSB check |
π Related Problemsβ
- Check if number is odd or even
- Count number of even digits in a number
- Separate even and odd indexed characters
- Find the sum of even or odd indexed elements
π¬