Problem Statement
You are given an integer, and need to find whether the integer is even or odd. While this might seem like a straightforward problem, optimizing the solution using bit manipulation can lead to more efficient and elegant code.
Example:
77 = odd,
44 = even
Traditionally, we check the parity of an integer by using the modulus operator (%). If the result is 0, the number is even; otherwise, it's odd. However, this approach involves division, which can be computational expensive. We aim to develop solution that relies on bitwise operations, making the process faster and more efficient.
Different Approaches
1️⃣ Traditional
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.
#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️⃣ 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.
#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.