Monday, October 6, 2025
HomeData Modelling & AIAlgorithms Quiz | Bit Algorithms | Question 4

Algorithms Quiz | Bit Algorithms | Question 4

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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32338 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6707 POSTS0 COMMENTS
Nicole Veronica
11871 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11936 POSTS0 COMMENTS
Shaida Kate Naidoo
6825 POSTS0 COMMENTS
Ted Musemwa
7089 POSTS0 COMMENTS
Thapelo Manthata
6779 POSTS0 COMMENTS
Umr Jansen
6781 POSTS0 COMMENTS