Write a function that takes an (unsigned) integer as input, and returns the number of bits that are equal to one in the binary representation of that number.java
Example: The binary representation of 1234
is 10011010010
, so the function should return 5
in this case.this
package poj; public class BitCounting { public static int countBits(int n){ String binaryStr = Integer.toBinaryString(n); int count = 0; for(int i=0; i<binaryStr.length(); ++i){ if(binaryStr.charAt(i) == '1'){ count++; } } return count; } }
package poj; import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class BitCountingTest { @Test public void testGame() { assertEquals(5, BitCounting.countBits(1234)); assertEquals(1, BitCounting.countBits(4)); assertEquals(3, BitCounting.countBits(7)); assertEquals(2, BitCounting.countBits(9)); assertEquals(2, BitCounting.countBits(10)); } }