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.
ExampleFor num = 5 you should return [0,1,1,2,1,2].
Follow upIt 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.
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?
应用公式f[i] = f[i/2] + (i%2);
并优化此公式为f[i] = f[i>>2] + (i&1),减少计算时间。
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
摘要:题目要求思路和代码这里除了暴力的计算每个数字中含有多少个,我们可以使用动态规划的方法来计算中有几个。还有一种等价的思路是第位的的个数或是加上位构成的数字的的个数。 题目要求 Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number ...
摘要:依次移位复杂度思路依次移动位数进行计算。代码利用性质复杂度,思路代码 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...
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...
摘要:空间复杂度方法是否为最大的幂的约数思路最大的的幂为,判断是否是的约数即可。复杂度时间复杂度,一个整数统计二进制的复杂度,最坏的情况下是。 大厂算法面试之leetcode精讲9.位运算视频教程(高效学习):点击学习目录:1.开篇介绍2.时间空间复杂度3.动态规划4.贪心5.二分查找6.深度优先&广度优先7.双指针...
摘要:移位法复杂度时间空间思路最简单的做法,原数不断右移取出最低位,赋给新数的最低位后新数再不断左移。代码分段相或法复杂度时间空间思路标准的源码。更好的优化方法是将其按照分成段存储,节省空间。 Reverse Bits Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (r...
阅读 1092·2021-10-27 14:13
阅读 2622·2021-10-09 09:54
阅读 810·2021-09-30 09:46
阅读 2380·2021-07-30 15:30
阅读 2139·2019-08-30 15:55
阅读 3390·2019-08-30 15:54
阅读 2826·2019-08-29 14:14
阅读 2751·2019-08-29 13:12