VOOZH about

URL: https://www.geeksforgeeks.org/dsa/3-ways-check-number-odd-even-without-using-modulus-operator-set-2-can-merge-httpswww-geeksforgeeks-orgcheck-whether-given-number-even-odd/

⇱ Check a number is odd or even without modulus operator - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check a number is odd or even without modulus operator

Last Updated : 31 May, 2022

Given a number, check whether it is even or odd.

Examples : 

Input: n = 11
Output: Odd

Input: n = 10
Output: Even
 

Method 1: Using Loop. 
The idea is to start with a boolean flag variable as true and switch it n times. If flag variable gets original value (which is true) back, then n is even. Else n is false.

Below is the implementation of this idea.  


Output: 
Odd

 

Time Complexity : O(n)

Auxiliary Space: O(1)

Method 2: By multiply and divide by 2. Divide the number by 2 and multiply by 2 if the result is same as input then it is an even number else it is an odd number.


Output : 
Odd

 

Time Complexity : O(1)

Auxiliary Space: O(1)

Method 3: Using Bitwise operator &. 
A better solution is to use bitwise operators. We need to check whether last bit is 1 or not. If last bit is 1 then the number is odd, otherwise always even.

Explanation: 

 input : 5 // odd
 00000101 
 & 00000001 
-------------- 
 00000001 
--------------

input : 8 //even
 00001000 
 & 00000001 
-------------- 
 00000000 
--------------


Below is the implementation of the idea. 


Output : 
Odd

 

Time Complexity : O(1)

Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: