leetcode解题报告:338. Counting Bits

来源:互联网 发布:贴片式温度传感器淘宝 编辑:程序博客网 时间:2024/05/27 21:50

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

难度:Medium

解题思路: 题目要求0-n每个数的二进制表示法中1的个数,注意到对于二进制表示法来说,每个偶数n的二进制中1的个数和它的一半的二进制表示法中1的个数是相同的,比如4的二进制位100而8的二进制位1000,1的个数都是1,对于奇数而言,每个奇数odd的二进制数中1的个数比odd/2向下取整用二进制表示法得到1的个数多1,比如7的二进制位111,而3的二进制为110.所以我们可以通过一次遍历,把0中1的个数0放在首元素,其它数通过上述方法得到。时间复杂度为O(n)

class Solution {public:    vector<int> countBits(int num) {        vector<int> ans;        ans.push_back(0);        for(int i = 1;i<=num;i++)        {            int x=i/2;            if(i%2==0)            ans.push_back(ans[x]);            else            ans.push_back(ans[x]+1);        }        return ans;    }};


0 0