Leetcode338. Counting Bits

原创 2017年01月03日 14:39:30

原题

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.

大意
给出一个整数nums,算出从0到nums中所有数的二进制中1的个数,并且以数组的形式返回。
思路
本来这道题没有思路,看了其他人的解法,才知道有一个数学公式,自己却没有想到,验证了一下,思路确实是正确的。第i位1的个数就是第i/2位+(i%2)的数值。
代码

public class Solution {
    public int[] countBits(int num) {
        int[]f=new int [num+1];
        for(int i=0;i<=num;i++){
            f[i]=f[i/2]+i%2;
        }
       return f; 
    }
}

原题链接

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Leetcode #338 - Counting bits - Medium

ProblemGiven a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calcula...

Leetcode 338. Counting Bits

338. Counting Bits Total Accepted: 23381 Total Submissions: 41506 Difficulty: Medium Given a ...

leetcode338:Counting Bits(medium)

经过一年的雁栖学习,终于回到了实验室,开始了研二的科研生活,是时候把我这一年的所学所想所思记录下来,以后我会慢慢更博,争取把以前和以后的学习生活记录下来! 昨天正式”刷”了第一道leetcode,以前...

LeetCode 338. Counting Bits

LeetCode 338. Counting Bits 分析与解答

Leetcode-338. Counting Bits

我的解法: 这道题是看了hinks然后才做出来的,而且还很慢,还是要多练习。 1.题意要素: (1)正整数 (2)时间复杂度O(n), 空间复杂度O(n), 不使用C++ ...

<LeetCode OJ> 338. Counting Bits

Total Accepted: 7119 Total Submissions: 12947 Difficulty: Medium Given a non negative integer n...

leetcode_middle_1_338. Counting Bits

题意: 给定一个非负整数n。从0到这个非负整数(共n+1个数),用一个数组返回这n+1个数的二进制表示的1的个数。 比如 3的二进制表示是11那么1的个数就是2. 分析: 列几个来看下: 0 、   ...

[leetcode]--338. Counting Bits

Question 338. Counting Bits Question: Given a non negative integer number num. For every numbers i...

Leetcode: 338.Counting Bits

Leetcode: 338.Counting Bits

leetcode(338). Counting Bits

problem Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num c...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)