Check if at least two out of three booleans are true

后端 未结 30 1919
自闭症患者
自闭症患者 2020-11-28 16:47

An interviewer recently asked me this question: given three boolean variables, a, b, and c, return true if at least two out of the three are true.

My solution follow

30条回答
  •  青春惊慌失措
    2020-11-28 17:48

    Rather than writing:

    if (someExpression) {
        return true;
    } else {
        return false;
    }
    

    Write:

    return someExpression;
    

    As for the expression itself, something like this:

    boolean atLeastTwo(boolean a, boolean b, boolean c) {
        return a ? (b || c) : (b && c);
    }
    

    or this (whichever you find easier to grasp):

    boolean atLeastTwo(boolean a, boolean b, boolean c) {
        return a && (b || c) || (b && c);
    }
    

    It tests a and b exactly once, and c at most once.

    References

    • JLS 15.25 Conditional Operator ? :

提交回复
热议问题