最近面试官问了我这个问题:给定三个布尔型变量a、b和c,如果其中至少有两个是true,则返回true。
我的解决方案如下:
boolean atLeastTwo(boolean a, boolean b, boolean c) {
if ((a && b) || (b && c) || (a && c)) {
return true;
}
else{
return false;
}
}
他说这还可以进一步改善,但如何呢?
最近面试官问了我这个问题:给定三个布尔型变量a、b和c,如果其中至少有两个是true,则返回true。
我的解决方案如下:
boolean atLeastTwo(boolean a, boolean b, boolean c) {
if ((a && b) || (b && c) || (a && c)) {
return true;
}
else{
return false;
}
}
他说这还可以进一步改善,但如何呢?
这个怎么样:
(a - b) ? c : a
public static boolean atLeastTrue(int amount, Boolean ... booleans) {
return Stream.of(booleans).filter(b -> b).limit(amount).count() == amount;
}
public static void main(String[] args){
System.out.println("1,2: " + atLeastTrue(1, true, false, true));
System.out.println("1,1: " + atLeastTrue(1, false, true));
System.out.println("1,0: " + atLeastTrue(1, false));
System.out.println("1,1: " + atLeastTrue(1, true, false));
System.out.println("2,3: " + atLeastTrue(2, true, false, true, true));
System.out.println("3,2: " + atLeastTrue(3, true, false, true, false));
System.out.println("3,3: " + atLeastTrue(3, true, true, true, false));
}
输出:
1,2: true
1,1: true
1,0: false
1,1: true
2,3: true
3,2: false
3,3: true
C:
if (!!a + !!b + !!c >= 2)
X = 或(a+b,c)
a b c X
1 1 0 1
0 0 1 1
0 1 1 1
函数ko
返回答案:
static int ho(bool a)
{
return a ? 1 : 0;
}
static bool ko(bool a, bool b, bool c)
{
return ho(a) + ho(b) + ho(c) >= 2 ? true : false;
}
在我看来,三个中的三似乎是相当任意的数字,而函数应该能够处理任意数量的数字。因此,为了回答这个问题,我会编写一个函数,用于判断数组中的 x 是否为真,例如:
bool istrue ( int x, bool[] list)
y = count true in list
return y >= x
public static boolean atLeast(int atLeastToBeTrue, boolean...bools){
int booleansTrue = 0;
for(boolean tmp : bools){
booleansTrue += tmp ? 1 : 0;
}
return booleansTrue >= atLeastToBeTrue;
}
你可以从 varargs
,也就是 boolean[]
中选择至少有多少个为真值 :-)
通过算术运算的帮助,这非常简单。
boolean a = true;
boolean b = false;
boolean c = true;
// Exactly One boolean value true.
if((a?1:0)+(b?1:0)+(c?1:0)==1)
return true;
else
return false;
// Exactly 2 boolean value true.
if((a?1:0)+(b?1:0)+(c?1:0)==2)
return true;
else
return false;
这就是您可以增加常量值以检查有多少布尔值为true
的方法。
function atLeastTwoTrue($a, $b, $c) {
int count = 0; count = ($a ? $count + 1 : $count); count = ($b ? $count + 1 : $count); count = ($c ? $count + 1 : $count); return ($count >= 2); }
使用三元运算符解决问题的最简形式是:
return a ? (b ? true : c) : (b ? c : false);
你可能也想要通过使用需求的双重否定来寻找解决方案,这意味着,你需要满足至多一个假值的条件,而不是至少两个真值。
a ? b||c : b&&c
。 - Don Hatch
atLeastTwo(iWantYou, iNeedYou, imEverGonnaLoveYou)
- Andrew GrimmatLeastTwo(0,2,0)
。请问您的看法? - Ken