Algorithms Quiz | Bit Algorithms | Question 4

Last Updated :
Discuss
Comments

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)));  } 
C
/* Incorrect function to check if x is power of 2*/ bool isPowerOfTwo (unsigned int x)  {   return (!(x&(x-1)));  }  
Java
// Incorrect function to check if x is power of 2 public static boolean isPowerOfTwo(unsigned int x) {  return (x & (x - 1)) == 0; } 
Python
# Incorrect function to check if x is power of 2 def is_power_of_two(x): return (x & (x - 1)) == 0 
JavaScript
// Incorrect function to check if x is power of 2 function isPowerOfTwo(x) {  return (x & (x - 1)) === 0; } 

What is wrong with above function?

It does reverse of what is required

It works perfectly fine for all values of x.

It does not work for x = 0

It does not work for x = 1

Share your thoughts in the comments