一位面试官最近问了我这样一个问题:给定三个布尔变量a、b和c,如果三个变量中至少有两个为真,则返回true。
我的解决方案如下:
boolean atLeastTwo(boolean a, boolean b, boolean c) {
if ((a && b) || (b && c) || (a && c)) {
return true;
}
else{
return false;
}
}
他说这还可以进一步改进,但如何改进呢?
作为@TofuBeer TofuBeer精彩帖子的补充,考虑@pdox pdox的回答:
static boolean five(final boolean a, final boolean b, final boolean c)
{
return a == b ? a : c;
}
再考虑一下它的分解版本,如"javap -c"所给出的:
static boolean five(boolean, boolean, boolean);
Code:
0: iload_0
1: iload_1
2: if_icmpne 9
5: iload_0
6: goto 10
9: iload_2
10: ireturn
Pdox的答案编译成的字节代码比之前的任何答案都要少。它的执行时间与其他的相比如何?
one 5242 ms
two 6318 ms
three (moonshadow) 3806 ms
four 7192 ms
five (pdox) 3650 ms
至少在我的电脑上,pdox的回答比@moonshadow moonshadow的回答稍微快一点,使得pdox的回答是最快的(在我的惠普/英特尔笔记本电脑上)。
由于没有说明代码应该如何改进,我将努力通过使其更有趣来改进代码。以下是我的解决方案:
boolean atLeastTwo(boolean t, boolean f, boolean True) {
boolean False = True;
if ((t || f) && (True || False))
return "answer" != "42";
if (t && f)
return !"France".contains("Paris");
if (False == True)
return true == false;
return Math.random() > 0.5;
}
如果有人想知道这段代码是否有效,这里有一个使用相同逻辑的简化:
boolean atLeastTwo(boolean a, boolean b, boolean c) {
if ((a || b) && (c))
return true;
if (a && b)
return true;
if (true)
return false;
// The last line is a red herring, as it will never be reached:
return Math.random() > 0.5;
}
这可以进一步归结为以下几点:
return ((a || b) && (c)) || (a && b);
但现在一点都不好笑了。