Problem: Check if a number is even or odd using bitwise operations
You are given an integer number. Your task is to determine whether the number is even or odd using the bitwise AND operator (&) without using the modulus operator (%).
Input:
- A single integer
number(−10^9 ≤number≤ 10^9).
Output:
- Print
number is even.if the number is even. - Print
number is odd.if the number is odd.
Example 1:
Input:
Enter an integer: 7
Output:
7 is odd.
Example 2:
Input:
Enter an integer: 12
Output:
12 is even.
Hint:
- The least significant bit (LSB) of an odd number is
1, while for an even number, it is0. You can use the bitwise AND operator to check the LSB.
Constraints:
- The integer is within the range −10^9 ≤
number≤ 10^9.
Code:
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// Check if the least significant bit is 1 (odd) or 0 (even)
if ((number & 1) == 1) {
printf("%d is odd.n", number);
} else {
printf("%d is even.n", number);
}
return 0;
}
Explanation of the Code:
- Bitwise AND (
&) with 1:- The least significant bit (LSB) of any odd number is
1, and the LSB of any even number is0. - By performing
number & 1, you isolate the LSB. - If the result is
1, the number is odd; if it’s0, the number is even.
- The least significant bit (LSB) of any odd number is
This approach avoids using the modulus operator (%) and works efficiently with bitwise operations.
