338. Counting Bits

Posted 鱼与海洋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

338. Counting Bits

[leetcode-338-Counting Bits]

338. Counting Bits

leetcode [338]Counting Bits

LeetCode 338. Counting Bits

LeetCode 338. Counting Bits