Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine whether number is odd or even without using conditional code

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.

like image 436
user3122903 Avatar asked Nov 27 '22 02:11

user3122903


2 Answers

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.

like image 181
Pshemo Avatar answered Dec 10 '22 22:12

Pshemo


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;
}
like image 41
Mureinik Avatar answered Dec 10 '22 22:12

Mureinik