[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: Odd

Input: 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:

  1. // C++ program to check for even or odd
    // using Bitwise XOR operator
      
    #include <iostream>
    using namespace std;
      
    // Returns true if n is even, else odd
    bool isEven(int n)
    {
      
        // n^1 is n+1, then even, else odd
        if (n ^ 1 == n + 1)
            return true;
        else
            return false;
    }
      
    // Driver code
    int main()
    {
        int n = 100;
        isEven(n) 
    ? cout << "Even" 
    : cout << "Odd";
      
        return 0;
    }
    Output :
    Even
    
  2. 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:

// C++ program to check for even or odd
// using Bitwise AND operator
  
#include <iostream> 
using namespace std; 
    
// Returns true if n is even, else odd 
bool isEven(int n) 
    // n&1 is 1, then odd, else even 
    return (!(n & 1)); 
    
// Driver code 
int main() 
    int n = 101; 
    isEven(n) 
? cout << "Even" 
: cout << "Odd"
    return 0; 
Output:
Odd

































 

Comments

Popular posts from this blog

[13 Feb 2020] Check if a given sequence of moves for a robot is circular or not

Important Program Collection

[16 Feb 2020] Given an array where every element occurs three times, except one element which occurs only once.