Monday, April 18, 2011

How to find whether a number is a power of 2 or not in Java?

There can be many possible solutions to this problem, but probably the most efficient remains to be the one which uses bit-level manipulation wisely.

We'll talk about only that solution here and since it involves bit-level manipulation of binary sequences, so should you require a refresh, first go through this article - 2's complement of negative number.

As is the case with many other solutions which use bits intelligently, this one is also very compact. That's the beauty of bit-handling. Let's first see what the solution is and then try to understand it. It becomes very easy to understand once you get the binary sequence representations right.

Java method to check if the passed parameter is a power of 2 or not

public boolean checkIfItsPowerOf2(int n){

 if( (n & -n) == n){
  
  //passed parameter is a power of 2
  return true;
 }
 else{
  //not a power of 2
  return false;
 }
}

Verify this method. :)

No comments:

Post a Comment

Chitika