I'm trying to construct a method to answer the below question. However I'm having a bit of trouble. Can someone assist me with this logic?
Write a static method odd() that takes three boolean inputs and returns true if an odd number of inputs are true, and false otherwise.
public boolean odd(boolean a, boolean b, boolean c)
    {   
        if((a && b) && (b && c) && (a && c))
            return true;
        if((a && b) && (b && c) || (a && b) && (a && c))
            return false;
         return false;
    }
Answer
I suggest you do something like
public boolean odd(boolean a, boolean b, boolean c) {
    int count = 0;
    if (a) count++;
    if (b) count++;
    if (c) count++;
    return count % 2 != 0;   
}
If you really want to optimize it, I think you want something like
if (a || b || c) {
    if (a && b && c) return true;
    if (a) return !(b && c);
    if (b) return !c;
    return c;
}
return false;
 
No comments:
Post a Comment