[LeetCode] Counting Bits

发布时间:2019-06-25 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了[LeetCode] Counting Bits脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

PRoblem

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

Follow up

IT is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

Hint

You should make use of what you have produced already.
Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range From previous.
Or does the odd/even status of the number help you in calculating the number of 1s?

Note

应用公式f[i] = f[i/2] + (i%2);
并优化此公式为f[i] = f[i>>2] + (i&1),减少计算时间。

Solution

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

脚本宝典总结

以上是脚本宝典为你收集整理的[LeetCode] Counting Bits全部内容,希望文章能够帮你解决[LeetCode] Counting Bits所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。