Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check positive or negative without using conditional statements in java

Tags:

java

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.

like image 438
OMGPOP Avatar asked Jun 29 '14 05:06

OMGPOP


People also ask

How do you check a number is positive or negative or zero in Java?

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.

How do you check if a number is positive or negative?

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.

How do you compare negative values in Java?

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.

Why do we need conditional statements in Java?

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.


1 Answers

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
like image 99
maaartinus Avatar answered Sep 18 '22 16:09

maaartinus