Search code examples
cbit-manipulationbitwise-operators

Check if integer is 0 with two restricted operations


I am trying to write a function isZero(int x) that returns 1 if x is 0, and returns 0 otherwise. How can I only do this with two of the following operators?

! ~ & ^ | + << >>


Solution

  • What about !!!x?

    Look at following diagram for values zero and different than zero:

          x == 0 | x <> 0
          -------+-------
    !x         1 |      0
    !!x        0 |      1
    !!!x       1 |      0
    

    Isn't that what you want?