Open In App

Algorithms Quiz | Bit Algorithms | Question 4

Last Updated : 28 Sep, 2018
Like Article
Like
Save
Share
Report

Consider the following code snippet for checking whether a number is power of 2 or not. 

C




/* Incorrect function to check if x is power of 2*/
bool isPowerOfTwo (unsigned int x)
{
  return (!(x&(x-1)));
}


What is wrong with above function?

(A)

It does reverse of what is required

(B)

It works perfectly fine for all values of x.

(C)

It does not work for x = 0

(D)

It does not work for x = 1



Answer: (C)

Explanation:

The logic behind this approach is that if a number is a power of 2, it will have only one bit set to 1 in its binary representation, and subtracting 1 from it will result in a binary number with all bits flipped to the right of that one bit. Performing a bitwise AND between these two numbers will result in 0, indicating that the number is a power of 2. 

However, there is a problem with this approach when the input is 0. In that case, the function will return true, even though 0 is not a power of 2. This is because 0 is the only number whose binary representation has no bits set to 1, so subtracting 1 from it will result in a binary number with all bits set to 1, and performing a bitwise AND between 0 and (0-1) will also result in 0. 

Therefore, the given function is incorrect as it does not handle the special case of 0. To fix this, we need to add a separate check for 0 at the beginning of the function and return false if the input is 0.

Please see https://www.geeksforgeeks.org/program-to-find-whether-a-no-is-power-of-two/

Hence Option (C) is the correct answer.


Quiz of this Question
Please comment below if you find anything wrong in the above post


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads