您好,欢迎来到爱玩科技网。
搜索
您的当前位置:首页LeetCode——338. Counting Bits

LeetCode——338. Counting Bits

来源:爱玩科技网

题目描述
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 1:

Input: 2
Output: [0,1,1]

Example 2:

Input: 5
Output: [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.

解题思路
题目直接求解很简单,但是题目要求时间复杂度为O(n),如果直接计算每个数字的二进制中1的个数肯定超过这个要求了。
首先可以很清楚的看出,f(0) = 0 以及f(1) = 1 。当要求2的二进制中1的个数的时候,考虑到2的二进制是10其实就是1左移了一位(乘2),同理4:100,是2(10)左移了一位。以此类推,可以得到偶数的1的个数 = 它除以2的结果中1的个数。
现在考虑奇数,2和3的区别就是在于最低位不同,只需要加上1即可。
注意可以使用位运算来提高运行速度。

代码实现

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

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- aiwanbo.com 版权所有 赣ICP备2024042808号-3

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务