338. Counting Bits

来源:互联网 发布:虎嗅网源码下载 编辑:程序博客网 时间:2024/05/16 16:00

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

首先,直接移动计算的时间复杂度太高了,不用考虑。

然后想到n&(n-1)操作可以实现计算二进制中1的个数。

class Solution {public:    vector<int> countBits(int num) {        vector<int>v(num+1,0);        for(int i=1;i<=num;i++){            int t=i,n=0;            while(t){                t=t&(t-1);                n++;            }            v[i]=n;        }        return v;    }};


AC之后,又去看了下别人的思路。还有个最快的方法。

即等于n-1的1的个数加上最右边的一位。

class Solution {public:    vector<int> countBits(int num) {        vector<int>v(num+1,0);        for(int i=1;i<=num;i++){            v[i]=v[i>>1]+i&1;        }        return v;    }};


0 0
原创粉丝点击