检查是否至少有三分之二的布尔值都是真实的 [英] Check if at least two out of three booleans are true
本文介绍了检查是否至少有三分之二的布尔值都是真实的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是面试官最近问我这个问题:有三次布尔变量,A,B和C,如果至少有两个出三个是真返回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.
我的解决方案如下:
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;
对于前pression本身,是这样的:
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 Conditional Operator ? :
这篇关于检查是否至少有三分之二的布尔值都是真实的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文