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.
Good one pushkar
i>>1%2==0 :P