How to find whether a number is odd or even, without using if
condition or ternary operators in Java?
This question is given by my teacher. He also give me a hint that it is possible by using a bitwise operator.
There are few ways to not use if
and get behavior that will be same as if if
was used, like ternary operator condition ? valueIfTrue : valueIfFalse
or switch/case
.
But to be tricky you can also use arrays and try to figure some transformation of our value to proper array index. In this case your code could look like
int number = 13;
String[] trick = { "even", "odd" };
System.out.println(number + " is " + trick[number % 2]);
output:
13 is odd
You can change number % 2
with number & 1
to use suggestion of your teacher. Explanation of how it works can be found here.
Consider a number's representation in binary format (E.g., 5 would be 0b101). An odd number has a "1" as its singles digit, an even number had a zero there. So all you have to do is bitwise-and it with 1 to extract only that digit, and examine the result:
public static boolean isEven (int num) {
return (num & 1) == 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With