Reputation: 53
Assuming that x is a positive integer, the following function returns 1 if x is a certain type of values or it returns 0 otherwise.
int mystery(int x) { return !((x-1) & x); }
What does mystery(20) return?
May I ask how do we approach this type of qn ? My idea is to express x in binary and do bitwise operation with it. Do correct me if I am wrong thanks !
Upvotes: 0
Views: 67
Reputation: 186
Let's work from the outside in.
!(expression)
you will get a 0 if expression is true, that is, not zero, and you will get a 1 if expression is false, that is, zero.
So when will expression be non-zero, giving a zero as a result? Whenever (x-1) has some bits in common with x.
What are examples?
It looks to me like we can say it returns 1 when the binary representation has exactly zero or one bits turned on in it.
0 or 1 or 10 or 100
Upvotes: 1