Java implementation LeetCode 338 bit count

338. bit count

Given a non-negative integer num. For 0 ≤ i ≤ i, each digital num range, which calculates the number of binary digits 1 and returns them as an array.

Example 1:

Input: 2
Output: [0,1,1]
Example 2:

Input: 5
Output: [0,1,1,2,1,2]
Advanced:

Given time complexity is O (n * sizeof (integer) ) answers very easy. But you can in linear time O (n) with one pass do it?
The space requirements of the algorithm complexity is O (n).
You can further improve the solution it? Request does not use any built-in functions (e.g., in __builtin_popcount C ++) in C ++ or any other language to do this.

The PS:
i & (i - 1) may be eliminated rightmost i a 1 (if any), and therefore i & (i - 1) is smaller than i, and i & (i - 1) has a number of in front counted, so the number i is one of i & (i - 1) number 1 plus 1

class Solution {
    public int[] countBits(int num) {
        int[] res = new int[num + 1];
        for(int i = 1;i<= num;i++){  //注意要从1开始,0不满足
            res[i] = res[i & (i - 1)] + 1;
        }
        return res;
    }
}
Released 1452 original articles · won praise 10000 + · views 1.73 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104737876