如果有三个Bool型变量,请写出一程序得知其中有2个以上变量的值是true

下面这篇文章是从StackOverflow来的。LZ面试的时候遇到了一道面试题:“如果有三个Bool型变量,请写出一程序得知其中有2个以上变量的值是true”,于是LZ做了下面的这样的程序: 

boolean atLeastTwo(boolean a, boolean b, boolean c) {
    if ((a && b) || (b && c) || (a && c)) {
        return true;
    } else {
        return false;
    }
}

面试官接着问到,请对你的这个程序改进一下,但LZ不知道怎么改进,于是上StackOverflow上问了一下,下面是StackOverflow上的众网友的回答。再往下看的时候,希望你自己能先想一想怎么改进。

有人说,如果你有下面这样的代码:

 if (someExpression) {
       return true;
   } else {
       return false;
   }

你应该改成:

     return someExpression;

所以,楼主的代码应该改成:

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

当然,解法不单单只有一种,还有下面的这些解决:

1)使用卡诺图

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

2)使用异或

1
return a ^ b ? c : a

这个方法难想到。

3)按照字面

1
(a?1:0)+(b?1:0)+(c?1:0) >= 2
1
a&&b || b&&c || a&&c

4)把Bool当成0和1

1
a&b | b&c | c&a
1
a + b + c <= 2

个方法很巧妙,如果是2个1和1个0. 两两相与后为 0 0 1 ,在或为1.

如果是3个1.都为1,相或还是为1.

5)如果bool不能当成0和1,则:

1
2
3
4
5
6
int howManyBooleansAreTrue =
(a ? 1 : 0)
+ (b ? 1 : 0)
+ (c ? 1 : 0);
 
return howManyBooleansAreTrue >= 2;

这个也是StackOverFlow上人贴出来的,我觉得写的挺清晰的
function atLeastTwoTrue($a, $b, $c) {
$count = 0;

if ($a) { $count++; }
if ($b) { $count++; }
if ($c) { $count++; }

if ($count >= 2) {
return true;
} else {
return false;
}
}

转自:http://coolshell.cn/articles/2514.html

类似题目:

输入1输出0,输入0输出1,有几种写法

x^1
!x
1-x
x?0:1
1>>x”

2.表驱动,这个也是瞬间进入脑海中,空间换时间。

  1: #include <iostream>
  2: #include <assert.h>
  3: 
  4: using namespace std;
  5: int main()
  6: {
  7:   int invert_table[] = { 1, 0};
  8:   int input;
  9:   
 10:   cin >> input;
 11:   //Well, Test the input if the valid index!!!
 12:   //I ignored & just use the assert macro
 13:   assert(input==0 || input ==1);

六:将传入的值加1取除以2的余数,其它代码不变,my_reverse函数代码如下。

[cpp] view plaincopy
 
  1. int my_reverse(int in)  
  2. {  
  3.     return (in + 1) % 2;  
  4. }  

参考:http://blog.csdn.net/skeleton703/article/details/7520609

 


原文地址:https://www.cnblogs.com/youxin/p/3348498.html