Suppose I have four variables x, y, z, w. I want to print:
"hello all non zero values" only if all x, y, z, w are non-negative and non-zero values.
If all the values are zero, then print "hello zero".
If any of the values (one, two or three but not all of them) is zero or negative then print "illegal values".
I've written a sample solution which handles and clubs negative as well as non-negative values:
if((x&y&z&w) == 0 && !(x==y && y==z && z==w && w==0)) {
System.out.println("illegal values");
} else {
System.out.println("hello all non zero values");
}
However, I am not able to handle the negative and positive values separately. Can anyone please suggest a solution for it?
CodePudding user response:
The bit-fiddling approach:
String s;
int j = w & x & y & z;
int k = w | x | y | z;
if (k == 0)
s = "hello zero";
else if (j != 0 && k > 0)
s = "hello all non-zero values";
else
s = "illegal values";
System.out.println(s);
This works because the bitwise-and is zero if any of the four values is zero, the bitwise-or is non-zero if any of the four values is non-zero; and the sign bit is set in the result (i.e., negative) if the sign bit is set in any of the four values.
(And I use the temporary 's' because why write 3 calls to the same routine)
Edited: this answer was updated after a recent edit to the question, which has clarified the criteria.
CodePudding user response:
It might help to reword your question in a different but equivalent way. You are basically printing "hello zero" if all of them are zero, "hello all non zero values" if all of them are positive, and "illegal values" in all other cases.
if (x == 0 && y == 0 && z == 0 && w == 0) {
System.out.println("hello zero");
} else if (x > 0 && y > 0 && z > 0 && w > 0) {
System.out.println("hello all non zero values");
} else {
System.out.println("illegal values");
}
CodePudding user response:
Something like this?
if (x > 0 && y > 0 && z > 0 && w > 0) {
System.out.println("hello all non zero values");
} else if (x == 0 && y == 0 && z == 0 && w == 0) {
System.out.println("hello zero");
} else {
System.out.println("illegal values");
}
CodePudding user response:
Does this work for you?
if ((x>0)&(y>0)&(z>0)&(w>0)) {
System.out.println("hello all non zero values");
} else {
System.out.println("illegal values");
}
Edit: this doesn't fully answer the question, my apologies