LeetCode-338:Counting Bits

来源:互联网 发布:查看被占用的端口 编辑:程序博客网 时间:2024/06/11 00:39

原题描述如下:

Given a non negative integer number num. For every numbersi 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]

题意给定一个数字,求从0到该数字,每一个数字对应二进制包含1的个数。

解题思路:移位。例子:5对应的二进制位101,则其位数为101向右移动以为的到的10包含的位数加上101的最低位(是1则总数加1,否则不加)

Java代码:

public class Solution {
    public int[] countBits(int num) {
        if(num == 0)return new int[]{0};
        if(num == 1)return new int[]{0, 1};
        
        int[] dp = new int[num+1];
        dp[1] = 1;
        
        for(int i=2; i<dp.length; ++i){
            dp[i] = (i&1) + dp[i>>1];
        }
        return dp;
    }
}
0 0