338. Counting Bits


  • Total Accepted: 74486 
  • Total Submissions: 123045 
  • Difficulty: Medium
  • Contributor: LeetCode

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.

解题思路:

看完题目之后首先想到的是从每个数字的二进制数着手。对所有n≥1,发现去掉最高位(必然为1)之后,都会和一个小于它的数相同,自然它们的1的个数也相同。那么对应的是哪个小于它的数呢?其实,去掉一个k位二进制数的最高位,就等于这个二进制数减去2^(k-1)。因此,用dp[i]记录i的二进制数中的1的个数,可以得到状态转移方程:

1. dp[0] = 0;

2. dp[i] = dp[i-2^(k-1)] + 1, i > 0.

因此可以得到一个时间复杂度和空间复杂度都是O(n)的算法。

0123456789
0000000100100011010001010110011110001001
1122444488

代码:

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> res(num + 1, 0);
        int power = 1;
        for(int i = 1; i <= num; i++){
            if(power * 2 == i)
                power *= 2;
            res[i] = res[i - power] + 1;
        }
        return res;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值