CountingBitsSolution { static int[] countBits(int num) { if (num < 0) return null; int[] result = new int[num + 1]; String binary; int count; for (int i = 0; i <= num; i++) { binary = Integer.toBinaryString(i); count = 0; for (char c : binary.toCharArray()) { if (c == '1') count++; } result[i] = count; } return result; }    }
@Test public void countingBits() { assertNull(CountingBitsSolution.countBits(-1)); assertEquals(0, CountingBitsSolution.countBits(0)[0]); int[] result = CountingBitsSolution.countBits(5); int[] except = new int[]{0, 1, 1, 2, 1, 2}; for (int i = 0; i < 5; i++) { assertEquals(except[i], result[i]); } long b = System.currentTimeMillis(); CountingBitsSolution.countBits(SUPPRESS_TEST_LIMITATION); long e = System.currentTimeMillis(); System.out.println(e - b); }