首页 > 代码库 > 338. Counting Bits

338. Counting Bits

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].

 

按位与 &

n & (n-1)

n&(n-1)作用:将n的二进制表示中的最低位为1的改为0,先看一个简单的例子:
n = 10100(二进制),则(n-1) = 10011 ==》n&(n-1) = 10000
可以看到原本最低位为1的那位变为0。

1、 判断一个数是否是2的方幂
n > 0 && ((n & (n - 1)) == 0 )

 

public class Solution {
    public int[] countBits(int num) {
        int[] res = new int[num+1];
        res[0] = 0;
        for(int i = 1; i <= num ; i++){
            System.out.println(i + " &  "+ (i & (i-1)) +" res is  "+ res[i & (i-1)]);
            res[i] = res[i & (i-1)] + 1;
        }
        return res;
    }
}

 

338. Counting Bits