Check whether a number x is nonzero using the legal operators except !.
Examples: isNonZero(3) = 1, isNonZero(0) = 0
Legal ops: ~ & ^ | + << >>
- Note : Only bitwise operators should be used.
if,else,for, etc. cannot be used. - Edit1 : No. of operators should not exceed 10.
- Edit2 : Consider size of
intto be 4 bytes.
int isNonZero(int x) {
return ???;
}
Using ! this would be trivial , but how do we do it without using ! ?
The logarithmic version of the adamk function:
And the fastest one, but in assembly:
Something similar to assembly version can be written in C, you just have to play with the sign bit and with some differences.
EDIT: here is the fastest version I can think of in C:
1) for negative numbers: if the sign bit is set, the number is not 0.
2) for positive:
0 - nwill be negaive, and can be checked as in case 1. I don’t see the-in the list of the legal operations, so we’ll use~n + 1instead.What we get: