Problem Statement
You are given an integer, and need to find whether the integer is even or odd.
Examples
Example 1:
Input: n = 4
Output: Even
Explanation: 4 is divisible by 2 -> Even
Example 2:
Input: n = 7
Output: Odd
Explanation: 7 is not divisible by 2 -> Odd
Example 3:
Input: n = 0
Output: Even
Explanation: 0 is considered an even number
Different Approaches
1️⃣ Traditional Approach
The traditional solution for checking if an integer is even or odd involves using the modulus operator (%
). We divide the number with 2, if remainder output is 0, the number is even, otherwise it is odd.
Approach:
- If
n % 2 == 0
, it’s even - Else, it’s odd
Code:
#include <iostream>
bool isEven(int num) {
return num % 2 == 0;
}
int main() {
int num = 77;
if (isEven(num)) {
std::cout << num << " is even." << std::endl;
} else {
std::cout << num << " is odd." << std::endl;
}
return 0;
}
// Output
77 is odd.
2️⃣ Using Bitwise AND (&1
) LSB Check
This solution checks if the least significant bit (LSB) of the binary representation of the integer. If the LSB is 0, the number is even; otherwise, it is odd.
Intuition:
- Even numbers have
0
as the least significant bit. - Odd numbers have
1
as the least significant bit. n & 1
checks whether the last bit is 1 (odd) or 0 (even)
Approach:
n & 1 == 0
→ evenn & 1 == 1
→ odd
#include <iostream>
bool isEvenLSB(int num) {
// Using bitwise AND to check the LSB
return (num & 1) == 0;
}
int main() {
int num = 44;
if (isEvenLSB(num)) {
std::cout << num << " is even." << std::endl;
} else {
std::cout << num << " is odd." << std::endl;
}
return 0;
}
// Output
44 is even.