Check if at least two out of three booleans are true

后端 未结 30 1927
自闭症患者
自闭症患者 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:50

    The most obvious set of improvements are:

    // There is no point in an else if you already returned.
    boolean atLeastTwo(boolean a, boolean b, boolean c) {
        if ((a && b) || (b && c) || (a && c)) {
            return true;
        }
        return false;
    }
    

    and then

    // There is no point in an if(true) return true otherwise return false.
    boolean atLeastTwo(boolean a, boolean b, boolean c) {
        return ((a && b) || (b && c) || (a && c));
    }
    

    But those improvements are minor.

提交回复
热议问题