Please explain question 4. I could not understand
Explanation of Q4
In this question you have to tell what this function does
the answer is " true if X is a power 2 "
Here is what the expression (x && !(x & (x - 1))); means:
- The initial
xpart meansx != 0 - The
(x & (x-1))part means "xis not a power of two" (i.e. is zero or has more than one bit set) - The
!(x & (x-1))expression means "xis a power of two"
Therefore, overall expression means " x is a positive power of two".
To see why x & (x-1) helps you find powers of two, consider what happens to numbers that have a single bit set vs. the numbers that have two or more bits set. A number with a single bit set, when decremented, would produce a sequence that looks like this:
000100000..000 <== x // when x is power of two
000011111..111 <== x-1
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.