My Simple Java Solution


  • 0
    Y

    The first bit always be set, so the current count is the preNum +1, And the preNum is the curNum reset the first bit. I use a mask to do this.

    public int[] countBits(int num) {
            int[] result = new int[num + 1];
            result[0] = 0;
            for (int i = 1, mask = 0; i <= num; i++) {
                result[i] = result[i & mask] + 1;
                int nextMask = (mask << 1) + 1;
                if (i == nextMask) {
                    mask = nextMask;
                }
            }
            return result;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.