Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (920 points)

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.

My solution follows:

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?

1 Answer

0 votes
by (13.2k points)

You can shorten down your code by providing an expression in the return statement itself, like, if the expressions value is true, true will be returned and if the value of expression is false, false will be returned.

            These are the few ways you can approach towards this problem,

1. 

 boolean atLeastTwo(boolean a, boolean b, boolean c) {

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

}

2.

boolean atLeastTwo(boolean a, boolean b, boolean c) {

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

}

3.

boolean atLeastTwo(boolean a, boolean b, boolean c) {

return a ^ b ? c : a

}

Related questions

0 votes
1 answer
0 votes
2 answers
asked Oct 3, 2019 in Python by Tech4ever (20.3k points)
0 votes
1 answer
asked Oct 12, 2019 in Python by Tech4ever (20.3k points)
0 votes
1 answer
0 votes
1 answer
asked Oct 28, 2019 in Java by Anvi (10.2k points)

Browse Categories

...