Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implement a method that takes 3 boolean args

Tags:

java

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?

like image 614
dcrearer Avatar asked Nov 28 '25 00:11

dcrearer


2 Answers

You can use XOR :

private static boolean odd(boolean x, boolean y, boolean z)
{
    return x ^ y ^ z;
}
like image 106
Eran Avatar answered Nov 30 '25 16:11

Eran


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;
}
like image 31
ug_ Avatar answered Nov 30 '25 16:11

ug_



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!