【LeetCode】338. Counting Bits (2 solutions)

本文介绍了一种算法挑战——计算从0到给定整数num范围内每个数字的二进制表示中1的数量,并返回这些数量组成的数组。讨论了两种解决方案,一种遵循直接计算的方法,另一种则利用了数字特性来提高效率。

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

 

Show Hint 

Credits:
Special thanks to @ syedee for adding this problem and creating all test cases.

 

解法一:

按照定义做,注意,x&(x-1)可以消去最右边的1

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> ret;
        for(int i = 0; i <= num; i ++)
            ret.push_back(countbit(i));
        return ret;
    }
    int countbit(int i)
    {
        int count = 0;
        while(i)
        {
            i &= (i-1);
            count ++;
        }
        return count;
    }
};

 

解法二:

对于[2^k, 2^(k+1)-1]区间,可以划分成前后两部分

前半部分与[2^(k-1), 2^k-1]内的值相同,后半部分与[2^(k-1), 2^k-1]内值+1相同。

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> ret;
        
        ret.push_back(0);
        if(num == 0)
        // start case 1
            return ret;
        ret.push_back(1);
        
        if(num == 1)
        // start case 2
            return ret;

        // general case
        else
        {
            int k = 0;
            int result = 1;
            while(result-1 < num)
            {
                result *= 2;
                k ++;
            }
            // to here, num∈ [2^(k-1),2^k-1]
            int gap = pow(2.0, k) - 1 - num;
            for(int i = 0; i < k-2; i ++)
            {// infer from [2^i, 2^(i+1)-1] to [2^(i+1), 2^(i+2)-1]
                // copy part
                for(int j = pow(2.0, i); j <= pow(2.0, i+1)-1; j ++)
                    ret.push_back(ret[j]);
                // plus 1 part
                for(int j = pow(2.0, i); j <= pow(2.0, i+1)-1; j ++)
                    ret.push_back(ret[j]+1);
            }
            for(int i = 0; i < pow(2.0, k-1) - gap; i ++)
            {
                int j = pow(2.0, k-2) + i;
                if(i < pow(2.0, k-2))
                // copy part
                    ret.push_back(ret[j]);
                else
                // plus 1 part
                    ret.push_back(ret[j]+1);
            }
        }
        return ret;
    }
};

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值