leetcode解题报告:338. 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].

难度: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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值