Elegantly determine if more than one boolean is “true”

前端 未结 22 1035
深忆病人
深忆病人 2020-12-04 13:40

I have a set of five boolean values. If more than one of these are true I want to excecute a particular function. What is the most elegant way you can think of that would al

22条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 14:44

    If you only have five different values, you can easily do the test by packing the bits in to a short or an int and checking to see if it is any of the zero or one bit answers. The only invalid numbers you could get would be..

    0x 0000 0000 
    0x 0000 0001
    0x 0000 0010
    0x 0000 0100
    0x 0000 1000
    0x 0001 0000
    

    This gives you six values to search for, put them in a lookup table and if it's not in there, you have your answer.

    This gives you a simple answer.

       public static boolean moreThan1BitSet(int b)
       {
          final short multiBitLookup[] = { 
                1, 1, 1, 0, 1, 0, 0, 0,
                1, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0,
                1, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0
          };
          if(multiBitLookup[b] == 1)
             return false;
          return true;
       }
    

    This doesn't scale well past 8 bits, but you only have five.

提交回复
热议问题