Friday, June 5, 2009

2 to the power of N

Here is a one-liner statement to check if a given integer is of 2 to the power of N.

public static boolean twoPowerN(int x){
return ((x & -x) == x) ? true : false;
}
You may try the method using this test case:
System.out.println(twoPowerN((int) Math.pow(2, 8)));

Basically it returns true for all integers 2powN, for example 2^100 or 2^7 or 2^33. A false will be returned for values other than 2powN. Well, that's the purpose of this method anyway (to check if a method is 2 to the power of N), right? :)

Have a good day everyone!

0 comments:

Post a Comment