Invalid solution for code challenge with operator restrictions

The following only assumes 2’s complement with at least 16 bits:

int mask = ~0x7FFF;
return !(x&mask)|!(~x&mask);

That uses a 15-bit constant; if that is too big, you can construct it from three smaller constants, but that will push it over the 8-operator limit.

An equivalent way of writing that is:

int m = 0x7FFF;
return !(x&~m)|!~(x|m);

But it’s still 7 operations, so int m = (0x7F<<8)|0xFF; would still push it to 9. (I only added it because I don’t think I’ve ever before found a use for !~.)

Leave a Comment