[03 Aug 2020] Check if a Number is Odd or Even using Bitwise Operators
Given a number N, the task is to check whether the number is even or odd using Bitwise Operators.
Examples:
Input: N = 11
Output: OddInput: N = 10
Output: Even
Using Bitwise XOR operator:
The idea is to check whether last bit of the number is set or not. If last bit is set then the number is odd, otherwise even.
As we know bitwise XOR Operation of the Number by 1 increment the value of the number by 1 if the number is even otherwise it decrements the value of the number by 1 if the value is odd.
Below is the implementation of the above approach:
- Output :
Even
- Using Bitwise AND operator:
The idea is to check whether the last bit of the number is set or not. If last bit is set then the number is odd, otherwise even.As we know bitwise AND Operation of the Number by 1 will be 1, If it is odd because the last bit will be already set. Otherwise it will give 0 as output.
Below is the implementation of the above approach:
Output:
Odd
Comments
Post a Comment