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 条件运算符?:
这篇关于检查三个布尔值中的至少两个是否为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检查三个布尔值中的至少两个是否为真
基础教程推荐
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
