Check if at least two out of three booleans are true(检查三个布尔值中的至少两个是否为真)
问题描述
一位面试官最近问我这个问题:给定三个布尔变量 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 条件运算符?:
这篇关于检查三个布尔值中的至少两个是否为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检查三个布尔值中的至少两个是否为真


- 如何使用WebFilter实现授权头检查 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01