一位面试官最近问了我这样一个问题:给定三个布尔变量a、b和c,如果三个变量中至少有两个为真,则返回true。
我的解决方案如下:
boolean atLeastTwo(boolean a, boolean b, boolean c) {
if ((a && b) || (b && c) || (a && c)) {
return true;
}
else{
return false;
}
}
他说这还可以进一步改进,但如何改进呢?
由于没有说明代码应该如何改进,我将努力通过使其更有趣来改进代码。以下是我的解决方案:
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);
但现在一点都不好笑了。
当我看到这个问题时,我的第一个想法是:
int count=0;
if (a)
++count;
if (b)
++count;
if (c)
++count;
return count>=2;
在看了其他帖子后,我承认
return (a?1:0)+(b?1:0)+(c?1:0)>=2;
更优雅。我想知道相对运行时是什么。
不过,无论如何,我认为这种解决办法比那种解决办法要好得多
return a&b | b&c | a&c;
variety because is is more easily extensible. What if later we add a fourth variable that must be tested? What if the number of variables is determined at runtime, and we are passed an array of booleans of unknown size? A solution that depends on counting is much easier to extend than a solution that depends on listing every possible combination. Also, when listing all possible combinations, I suspect that it is much easier to make a mistake. Like try writing the code for "any 3 of 4" and make sure you neither miss any nor duplicate any. Now try it with "any 5 of 7".