检查三个布尔值中的至少两个是否为真
一位面试官最近问我这个问题:给定三个布尔变量 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);
}
a
和 b
只测试一次,c
最多测试一次.
It tests a
and b
exactly once, and c
at most once.
- JLS 15.25 条件运算符?:
相关文章