Thursday 13 August 2015

Count all unset bits in an integer


For example, 4 = 100 (in binary). Total un set bits are 1.
public class UnsetBits {

 public static int getUnsetBits(int num) {
  int count = 0;

  if (num == 0)
   return 1;

  while (num > 0) {
   if ((num & 1) == 0)
    count = count + 1;
   num = num >> 1;
   System.out.println(num);
  }

  return count;
 }
}


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

import org.junit.Test;

public class UnsetBitsTest {
 @Test
 public void test1(){
  assertEquals(UnsetBits.getUnsetBits(0), 1);
  assertEquals(UnsetBits.getUnsetBits(1), 0);
  assertEquals(UnsetBits.getUnsetBits(2), 1);
  assertEquals(UnsetBits.getUnsetBits(3), 0);
  assertEquals(UnsetBits.getUnsetBits(4), 2);
  assertEquals(UnsetBits.getUnsetBits(5), 1);
  assertEquals(UnsetBits.getUnsetBits(6), 1);
  assertEquals(UnsetBits.getUnsetBits(7), 0);
  assertEquals(UnsetBits.getUnsetBits(8), 3); 
 }
}


No comments:

Post a Comment