/***************************************************************************
* Author: Isai Damier
* Title: isPowerOfTwo
* Project: geekviewpoint
* Package: algorithms
*
* Statement:
* Indicate whether the given integer n is a power of two.
*
* Sample Input: 16
* Sample Output: true
*
* Technical Details:
* A number that is a power of two only has one set bit: 0 = 0; 2 = 10;
* 4 = 100; 8 = 1000; 16 = 10000; etc. Therefore checking whether a number
* is a power of two is as simple as clearing the lowest set bit and then
* checking that the result is equal to zero. (ref to clearLowestBit above)
*
***************************************************************************/
public boolean isPowerOfTwo(int n) {
return 0 == (n & (n - 1));
}
import org.junit.Test;
import static org.junit.Assert.*;
public class BitwiseTest {
/**
* Test of isPowerOfTwo method, of class Bitwise.
*/
@Test
public void testIsPowerOfTwo() {
System.out.println(""isPowerOfTwo"");
Bitwise bits = new Bitwise();
for (int i = 1; i < 31; i++) {
assertTrue(bits.isPowerOfTwo((int) Math.pow(2, i)));
}
}
}