Elegantly determine if more than one boolean is “true”

前端 未结 22 1046
深忆病人
深忆病人 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:20

    If your flags are packed into one word then Michael Burr's solution will work. However, the loop is not necessary:

    int moreThanOneBitSet( unsigned int v)
    {
        return (v & (v - 1)) != 0;
    }
    

    example

     v (binary) | v - 1 | v&(v-1) | result
    ------------+-------+---------+--------
           0000 |  1111 |    0000 |  false
           0001 |  0000 |    0000 |  false
           0010 |  0001 |    0000 |  false
           0011 |  0010 |    0010 |   true
           .... |  .... |    .... |   ....
           1000 |  0111 |    0000 |  false
           1001 |  1000 |    1000 |   true
           1010 |  1001 |    1000 |   true
           1011 |  1010 |    1010 |   true
           1100 |  1011 |    1000 |   true
           1101 |  1100 |    1100 |   true
           1110 |  1101 |    1100 |   true
           1111 |  1110 |    1110 |   true
    

提交回复
热议问题