I'm studying "Programming in Java An Interdisciplinary Approach by Sedgewick and Wayne". The following question is giving me a bit of a challenge to implement.
Write a static method odd() that takes three boolean inputs and returns true if an odd number of inputs are true, and false otherwise.
private static boolean odd(boolean x, boolean y, boolean z)
{
if((x && y) && z)
return true;
else if((x) && !y && !z)
return true;
else if((y) && !x && !z)
return true;
else if((z) && !x && !y)
return true;
else
return false;
}
Could I have implemented this a different way?
You can use XOR :
private static boolean odd(boolean x, boolean y, boolean z)
{
return x ^ y ^ z;
}
I think the simplest way would be to make your booleans to int values and add them up.
private static boolean odd(boolean x, boolean y, boolean z) {
int sum = 0;
if(x) sum++;
if(y) sum++;
if(z) sum++;
// check if its odd.
return sum % 2 != 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