题目:三个boolean值至少两个为ture,则判为true

题目描述:

三个boolean值至少两个为ture,则判为true。

解题思路:

这题是朋友问我的一个问题,网上查了下,发现是一道面试题。该题的解决方案有很多,我使用的方法如下表格所示。
首先求出 a 异或 b,然后发现,当 a \(\oplus\) b = 0 的时候,结果为 a 的值;当 a \(\oplus\) b = 1 的时候,结果为 c 的值。

a \(\oplus\) b a b c result
0 \(\color{red}{\underline{1}}\) 1 1 1
0 \(\color{red}{\underline{1}}\) 1 0 1
1 1 0 \(\color{red}{\underline{1}}\) 1
1 0 1 \(\color{red}{\underline{1}}\) 1
0 \(\color{red}{\underline{0}}\) 0 1 0
1 0 1 \(\color{red}{\underline{0}}\) 0
1 1 0 \(\color{red}{\underline{0}}\) 0
0 \(\color{red}{\underline{0}}\) 0 0 0
public boolean atLeastTwo(boolean a, boolean b, boolean c) {
    return a ^ b ? c : a;
}

另外还有多种解法。 网上搜到的: https://blog.csdn.net/m0_38098232/article/details/73457120

解法1:

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

解法2:

return (a==b) ? a : c;
posted @ 2020-03-12 18:10  我是宵夜  阅读(284)  评论(0编辑  收藏  举报