Finding Odd And Even Numbers Using Bitwise AND(&)
In this chapter, we will explore how the bitwise AND operator can be employed to determining whether a number is odd or even.
Understanding Bitwise AND
The bitwise AND operator (&) compares each bit of its operands and returns a new binary number. Each bit in the resulting number is 1 if both corresponding bits in the operands are 1; otherwise, it is 0.
For example
5 & 3 evaluates to 1 because:
Binary representation of 5 is 101.
Binary representation of 3 is 011.
Performing bitwise AND results in 001, which is 1 in decimal.
Determining Odd and Even Numbers
In binary representation, even numbers always end with 0 and odd numbers end with 1. This property allows us to use the bitwise AND operator to check the least significant bit (LSB) of a number. Specifically, we can use the number 1 (binary 0001) to isolate the LSB of any integer:
If a number is even, its LSB is 0, and performing a bitwise AND with 1 will yield 0.
If a number is odd, its LSB is 1, and performing a bitwise AND with 1 will yield 1.
Example
Even number : 4 (binary 0100):
4 & 1 results in 0 because 0100 & 0001 is 0000.
Odd number : 7 (binary 0111):
7 & 1 results in 1 because 0111 & 0001 is 0001.
Approach
Input
Accept an integer from the user.
Bitwise Operation
Use the bitwise AND operator with 1 to check the LSB of the input number.
Output
Print whether the number is odd or even based on the result of the bitwise operation.
Step-by-Step Solution and Code
Here’s how you can implement this in Java:
Explanation
Import Scanner
The Scanner class is imported to handle user input.
Create Scanner Object
An instance of Scanner is created to read user input from the console.
Prompt for Input
The user is prompted to enter an integer.
Bitwise AND Operation
The entered integer is subjected to a bitwise AND operation with 1.
If the result is 0, the number is even.
If the result is 1, the number is odd.
Output Result
Based on the result of the bitwise operation, the program prints whether the number is odd or even.
Close Scanner
The scanner object is closed to prevent resource leaks.
Significance
Using the bitwise AND operator for checking odd and even numbers offers several advantages:
Efficiency
Bitwise operations are generally faster than arithmetic operations, making them suitable for performance-critical applications.
Simplicity
The logic is straightforward and easy to understand, relying on the inherent properties of binary representation.
Conclusion
Understanding and leveraging bitwise operations, such as the AND operator, can lead to more efficient and elegant solutions in programming. Determining the parity (odd or even) of a number using bitwise AND is a prime example of how these operations can simplify and speed up common tasks.