Today's Question:  What's your opinion about Alibaba mooncake incident?        GIVE A SHOUT

Technical Article => Programming =>  Algorithm

A boolean value interview question

  陈皓      2012-04-30 08:49:32      3,910    0    0

Someone asked a question on StackOverflow, he was asked an interview question. The question is : Given 3 boolean variables a, b, c, return true if at least 2 out of the 3 are true. He gave the solution as follows :
boolean atLeastTwo(boolean a, boolean b, boolean c) {
    if ((a && b) || (b && c) || (a && c)) {
        return true;
    } else {
        return false;

Then the interviewer asked him to improve the solution given and make it more concise. He didn't know how to improve the solution, so he posted the question on StackOverflow. There are some people who gave very useful solutions. I think this is deserved to be discussed here for us to better understand boolean values and expressions in programming. Here I share some of these solutions with you.

Some one says if you have some code snippet like
   if (someExpression) {
       return true;
   } else {
       return false;

You should modify it as      
So the solution can be improved as    
   return ((a && b) || (b && c) || (a && c));

Of course there are some other excellent solutions. Such as Tim Stone gave the solution
   return a ^ b ? c : a
Personally I think this solution is the most concise one.

Also if we use Karnaugh map, we can have

return a ? (b || c) : (b && c);

If we can treat bool values a 1 or 0, then we have
a&b | b&c | c&a
a + b + c >= 2

If we cannot treat bool values as 1 or 0, then we have
int howManyBooleansAreTrue =
(a ? 1 : 0)
+ (b ? 1 : 0)
+ (c ? 1 : 0);
return howManyBooleansAreTrue >= 2;
(Shareded by danatel)

Here is one more brilliant answer
(a==b) ? a : c;
Want to try yourself? Put your answer here.

Author :  Source : Original source :



Share on Facebook  Share on Twitter  Share on Google+  Share on Weibo  Share on Reddit  Share on Digg  Share on Tumblr    Delicious



No comment for this article.


What an embarrassment

By sonic0002
When someone wants to hire someone with 7-10 years NodeJS experience, the NodeJS author jumped out and said that he had just 7 years experience of NpdeJS because NodeJS was created in 2009, which is 7 years ago. What an embarrassment for the recruiter.