Check positive or negative without using conditional statements in Java
I had an interview question last week:
I need a function to print whether a number is positive or negative without using conditional statements. If not, it is used to switch a? b: C wait, how can I do this?
I told the interviewer that it was impossible to say that the problem was "conditional" in nature He told me it was possible, but he didn't tell me how I did quite a lot of searches, but I didn't have a good answer
Solution
One possible solution:
String[] responses = {"Positive","Negative"}; System.out.println(responses[(i >> 31) & 1]);
This is also a positive number
Because integers in Java need to be stored in two's complexity (or behave like them), the highest bit of any negative number is 1 and the highest bit of any other number is 0 (I > 31) copy the highest bit to every other bit (so the negative number becomes 11111111111111111111111111111111111, and the positive / zero sign becomes 00000000 00000000 00000000)& Ampere; 1 set all bits except the lowest bit to 0 Combination (I > 31) & 1 effectively reads only the highest bit of I