资讯专栏INFORMATION COLUMN

[LeetCode] Counting Bits

cyixlq / 3029人阅读

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;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/66012.html

相关文章

  • leetcode 338. Counting Bits

    摘要:题目要求思路和代码这里除了暴力的计算每个数字中含有多少个,我们可以使用动态规划的方法来计算中有几个。还有一种等价的思路是第位的的个数或是加上位构成的数字的的个数。 题目要求 Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number ...

    ShevaKuilin 评论0 收藏0
  • LeetCode[191] Number of 1 Bits

    摘要:依次移位复杂度思路依次移动位数进行计算。代码利用性质复杂度,思路代码 LeetCode[191] Number of 1 Bits Write a function that takes an unsigned integer and returns the number of ’1 bits it has (also known as the Hamming weight). Fo...

    Scliang 评论0 收藏0
  • [LeetCode] 191. Number of 1 Bits

    Problem Number of 1 BitsWrite a function that takes an unsigned integer and returns the number of ’1 bits it has (also known as the Hamming weight). Example For example, the 32-bit integer 11 has bina...

    gitmilk 评论0 收藏0
  • 大厂算法面试之leetcode精讲9.位运算

    摘要:空间复杂度方法是否为最大的幂的约数思路最大的的幂为,判断是否是的约数即可。复杂度时间复杂度,一个整数统计二进制的复杂度,最坏的情况下是。 大厂算法面试之leetcode精讲9.位运算视频教程(高效学习):点击学习目录:1.开篇介绍2.时间空间复杂度3.动态规划4.贪心5.二分查找6.深度优先&广度优先7.双指针...

    番茄西红柿 评论0 收藏2637
  • [Leetcode] Reverse Bits 反转位

    摘要:移位法复杂度时间空间思路最简单的做法,原数不断右移取出最低位,赋给新数的最低位后新数再不断左移。代码分段相或法复杂度时间空间思路标准的源码。更好的优化方法是将其按照分成段存储,节省空间。 Reverse Bits Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (r...

    notebin 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<