Example: Counting Bits - rFronteddu/general_wiki GitHub Wiki

Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.

class Solution {
    public int[] countBits(int n) {
        int[] result = new int[n+1];
        for (int i = 0; i <= n; i++) {
            int count = 0;
            long j = Integer.toUnsignedLong(i);
            while (j > 0) {
                count += j & 1;
                j >>= 1;
            }
            result[i] = count;
        }
        return result;
    }
}