338. Counting Bits

Given a non negative integer numbernum. For every numbersiin the range0 ≤ i ≤ numcalculate the number of 1's in their binary representation and return them as an array.

Example:
Fornum = 5you should return[0,1,1,2,1,2].

Follow up:

  • It is very easy to come up with a solution with run timeO(n*sizeof(integer)). But can you do it in linear timeO(n)/possibly in a single pass?
  • Space complexity should beO(n).

  • Can you do it like a boss? Do it without using any builtin function like__builtin_popcountin c++ or in any other language.

Hint:

  1. You should make use of what you have produced already。

因为最近在研究树状数组,被他的精妙所震撼。他巧妙的将一个数的二进制0与1的个数赋予新的含义。
int LowBit(int x)
	{
		return x & (-x);
	}

树状数组学习笔记:

看到了这个题,很自然的联想到LowBit的使用。
思路:记忆化搜索+LowBit

对于LowBit(x):
假设x的末尾0的个数为k则LowBit是计算2^k,同时也是计算末尾1在的位置(即所表示的数)
ibit2^k
1011
2102
3111
41004
51011
61102
71111
810008
910011
1010102
1110111
1211004
1311011
1411102
1511111
161000016
0特殊处理下,直接输出0
当i与2^k相等时,意味着只有一个1,输出1
当i与2^k不相等时,比如我们看i=15,此时2^k=1,即末尾的1代表1,我们把末尾的1“去掉”,1111-->1110
即转化为求14的二进制数1的个数(当然得加上删除的1),也就是我们得利用先前求得的来计算i的二进制数1的个数。

#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
	int LowBit(int x)
	{
		return x & (-x);
	}
    vector<int> countBits(int num) {
        vector<int>vec;
        vec.push_back(0);
        for (int i = 1; i <= num; ++i)
        {
        	if (i == LowBit(i))
        	{
        		vec.push_back(1);
        	}
        	else
        	{
        		vec.push_back(vec[i - LowBit(i)] + 1);
        	}
        }
        return vec;
    }
};

int main()
{
	Solution s;
	vector<int>vec = s.countBits(16);
	for (auto iter = vec.begin(); iter != vec.end(); iter++)
	{
		cout << *iter << endl;
	}
    return 0;
}

63ms

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值