Thursday, 13 August 2015

Count all set bits in an integer


For example, 9 = 1001 (in binary). Total set bits are 2.

public class SetBits {
 public static int getNumSetBits(int num) {
  int count = 0;

  while (num > 0) {
   count = count + (num & 1);
   num = num >> 1;
  }
  return count;
 }
}


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

import org.junit.Test;

public class SetBitsTest {
 @Test
 public void test1(){
  assertEquals(SetBits.getNumSetBits(0), 0);
  assertEquals(SetBits.getNumSetBits(1), 1);
  assertEquals(SetBits.getNumSetBits(2), 1);
  assertEquals(SetBits.getNumSetBits(3), 2);
  assertEquals(SetBits.getNumSetBits(4), 1);
  assertEquals(SetBits.getNumSetBits(5), 2);
  assertEquals(SetBits.getNumSetBits(6), 2);
  assertEquals(SetBits.getNumSetBits(7), 3);
  assertEquals(SetBits.getNumSetBits(8), 1); 
 }
}


No comments:

Post a Comment