Check if at least two out of three booleans are true

后端 未结 30 1806
自闭症患者
自闭症患者 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条回答
  •  -上瘾入骨i
    2020-11-28 17:26

    Another example of direct code:

    int  n = 0;
    if (a) n++;
    if (b) n++;
    if (c) n++;
    return (n >= 2);
    

    It's not the most succinct code, obviously.

    Addendum

    Another (slightly optimized) version of this:

    int  n = -2;
    if (a) n++;
    if (b) n++;
    if (c) n++;
    return (n >= 0);
    

    This might run slightly faster, assuming that the comparison against 0 will use faster (or perhaps less) code than the comparison against 2.

提交回复
热议问题