What does the following function check?
Answer :
(C) v is a power of 2
Explanation :
1) If v is a power of 2,
Written by Munia Balayil
bool f(unsigned int v)
{
return ((v!=0)&&!(v & v-1));
}
(A) v is an odd number
(B) v is a multiple of 2
(C) v is a power of 2
(D) v has a 0 bitAnswer :
(C) v is a power of 2
Explanation :
1) If v is a power of 2,
- v is never 0 (even 2^0 = 1) and (v != 0) will always be 1(True).
- (v & v-1) will always be 0(False) and hence their negation will always be 1(True).
2) If v is not a power of 2, either
- v = 0, or
- (v & v-1) is something other than 0 and their negation is 0(False)
Written by Munia Balayil
No comments:
Post a Comment