Skip to main content

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 & 1 is 1, then the number is odd.
    • If n & 1 is 0, then the number is even.
  • We use ! to negate the result, so:
    • !(n & 1) returns true for even numbers,
    • false for 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​

ComplexityValue
TimeO(1)
SpaceO(1)

⚠️ Edge Cases​

  • Negative numbers are correctly handled by bitwise operations in C++.
  • Zero is considered even (since LSB is 0).

πŸ’‘ Other Approaches​

ApproachExampleDescription
Modulon % 2 == 0Simple and readable, but slightly slower due to division
Bitmasking!(n & 1) βœ…Fast and efficient using LSB check

  • 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

πŸ’¬

Discussion & Doubts