How to check whether an integer is an odd number or not ?

Solution 1:

public static boolean isOdd(int i) { 

 return i % 2 == 1;

}

It seems to be correct but only for positive integers, it will fail if "i" is a negative number. So how to fix it, see below solution.

Solution 2: Just reverse the sense of comparison.

public static boolean isOdd(int i) { 

  return i % 2 != 0; 

}

Solution 3: If you concern about the performance then use this.

public static boolean isOdd(int i) { 
  
  return (i & 1) != 0; 

}

Reason :

Remember as a general rule, the divide and remainder operations are slow compared to other arithmetic and logical operations.




Learner the same thing today, bitwise operators are much faster than any other operator , had a revision with this post . Nowadays in the race of competitive programming , ranks and hackathons, I believe most of us are forgetting the core basics of language and compilers. :)

Pushkar Kumar sir, that's an excellent article!☺️ I would like to suggest 2 more alternative solutions to it- 1.Start with a boolean flag variable as true and switch it n times. If flag variable gets original value (i.e.True) back => n is even. Else -n is false. bool isEven(int n) { bool isEven = true; for (int i=1; i <= n; i++) isEven = !isEven; return isEven; } 2. Multiply and divide by 2. Divide the number by 2 and multiply by 2 -if the result is same as input => it is an even number else -it's an odd number. bool isEven(int n) { return ((n / 2) * 2 == n); } Choose the best among the given options! Thanks.

To view or add a comment, sign in

More articles by Pushkar Kumar

  • Java Productivity with Lombok: A Comprehensive Guide

    Java, as one of the most widely used programming languages, offers robust features for building enterprise-grade…

    5 Comments
  • Engineering Blogs

    It is always great to see great software companies out there with an open culture who like to share their experiences…

    11 Comments
  • 4 Pillars for Object Oriented Programming.

    The four pillars for OOP are Abstraction, Encapsulation, Inheritance, Polymorphism. Abstraction : Abstraction is the…

    21 Comments
  • Creating Deadlock in Java in a single statement

    Today I learnt, how to create a deadlock in java by using a single statement. /**  *  * @author Pushkar Kumar…

    9 Comments

Explore content categories