检查三个布尔值中的至少两个是否为真 [英] Check if at least two out of three booleans are true

查看:29
本文介绍了检查三个布尔值中的至少两个是否为真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一位面试官最近问我这个问题:给定三个布尔变量 a、b 和 c,如果三个中至少有两个为真,则返回真.

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.

我的解决方案如下:

boolean atLeastTwo(boolean a, boolean b, boolean c) {
    if ((a && b) || (b && c) || (a && c)) {
        return true;
    }
    else{
        return false;
    }
}

他说这可以进一步改进,但是如何呢?

He said that this can be improved further, but how?

推荐答案

而不是写:

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

写:

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);
}

ab 只测试一次,c 最多测试一次.

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

这篇关于检查三个布尔值中的至少两个是否为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆