0 votes
1 view
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
1 answer
0 votes
1 answer
asked Oct 28, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...