检查三个布尔值中是否至少有两个是真的

本文翻译自:Check if at least two out of three booleans are true

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. 一位采访者最近问我这个问题:给定三个布尔变量a,b和c,如果三个中至少有两个为真,则返回true。

My solution follows: 我的解决方案是:

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? 他说这可以进一步改善,但如何?


#1楼

参考:https://stackoom.com/question/CuEA/检查三个布尔值中是否至少有两个是真的


#2楼

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. 它只测试ab一次,最多c次测试一次。

References 参考


#3楼

Why not implement it literally? 为什么不按字面意思实现呢? :) :)

(a?1:0)+(b?1:0)+(c?1:0
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值