Thursday 13 August 2015

How to know whether a number is power of 2


Number
Binary
Number-1
Binary
2
00000010
1
00000001
4
00000100
3
00000011
8
00001000
7
00000111
16
00010000
15
00001111
32
00100000
31
00011111


If n is a power of 2, then n&(n-1) is equal to 0.
public class PowerOfTwo {
 public static boolean isPowerOfTwo(int n) {
  return ((n & (n - 1)) == 0);
 }
}


Following is the junit test case for above program.
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class PowerOfTwoTest {

 @Test
 public void test1() {
  assertTrue(PowerOfTwo.isPowerOfTwo(2));
  assertTrue(PowerOfTwo.isPowerOfTwo(4));
  assertTrue(PowerOfTwo.isPowerOfTwo(8));
  assertTrue(PowerOfTwo.isPowerOfTwo(16));
  assertTrue(PowerOfTwo.isPowerOfTwo(32));
  assertTrue(PowerOfTwo.isPowerOfTwo(64));
  assertTrue(PowerOfTwo.isPowerOfTwo(1));

  assertFalse(PowerOfTwo.isPowerOfTwo(3));
  assertFalse(PowerOfTwo.isPowerOfTwo(5));
  assertFalse(PowerOfTwo.isPowerOfTwo(6));
  assertFalse(PowerOfTwo.isPowerOfTwo(7));
 }
}


No comments:

Post a Comment