An interview question I was asked last week:
I need a function to print out whether a number is positive or negative without using conditional statements like if else
while
for
switch
a? b:c
etc. How can i do that.
I told the interviewer that it's impossible cuz the question is 'conditional' in nature. He told me it's possible but didn't tell me how. I did quite a bit of search but no good answers.
Java Integer class provides an inbuilt function signum() to check if a number is positive or negative. It is a static method that accepts a parameter of integer type. It returns 0, if the argument is 0.
If a number is greater than zero, it is a positive number. If a number is less than zero, it is a negative number. If a number equals to zero, it is zero.
To check if a number is negative, use comparison operator: less than (<) that accepts the number and zero as operands. If number is less than zero, it returns true, else it returns false.
You can use these conditions to perform different actions for different decisions. Java has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false.
Just to elaborate on immibis' answer a bit:
int index(int i) {
return 1 + (i>>31) - (-i>>31);
}
String[] text = {"negative", "zero", "positive"};
private String text(int i) {
return text[index(i)];
}
The signed shift i>>31
converts every negative number into -1
and every other into 0
. Computing -i>>31
allows to tell positive numbers from non-positive ones. Now look at the computed index
:
positive: 1 + 0 - (-1) = 2
zero: 1 + 0 - 0 = 1
negative: 1 + (-1) - 0 = 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