Skip to content

338. Counting Bits

Jacky Zhang edited this page Aug 22, 2016 · 1 revision

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.

Example:
For num = 5 you should return [0,1,1,2,1,2].

解题技巧为Dynamic Programming。 注意到[2-3]比[0-1]多一个1,[4-7]比[0-3]多一个1,[8-15]比[0-7]多一个1... 因此可采用two points,每到power of 2的位置,都让其中一个指针归0,然后依次加一即可。

public class Solution {
    public int[] countBits(int num) {
        int[] count = new int[num+1];
        count[0] = 0;
        int pow = 1;
        for(int i = 1, t = 0; i <= num; i++, t++) {
            if(i == pow) {
                pow *= 2;
                t = 0;
            }
            count[i] = count[t] + 1;
        }
        return count;
    }
}
Clone this wiki locally