本文翻译自: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. 它只测试a
和b
一次,最多c
次测试一次。
References 参考
#3楼
Why not implement it literally? 为什么不按字面意思实现呢? :) :)
(a?1:0)+(b?1:0)+(c?1:0