LeetCode338. Counting Bits题解

1. 题目描述

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.
【翻译过来】:给定一格非负整数i,需要输出从0-i,每个数对应二进制中1的个数。

2. 样例

num = 5
return [0,1,1,2,1,2]

3. 分析

其实题目理解起来非常简单:从0到i,我们需要每个数去计算其二进制里面1的个数,然后存储起来返回输出即可。

3.1. 普通算法

每个数计算二进制中1的个数可以使用模二的方法:该数不停除以2直到为0,在过程中如果当前数不能被2整除,则该位置就有一个1,使用一格计数器counter计算1的个数即可。

3.2. 相与的方法

每一个数i与i-1相与造成的效果都是:相与结果里面1的个数比i里面1的个数要少一个,即1的个数的表达式可以表示为:

array[i] - 1 = array[i&(i-1)]
array[i] = array[i&(i-1)] + 1

这里写图片描述

4. 源码

4.1. 普通算法

class Solution {
public:
    int getBinaryOne(int num) {
        int counter = 0;
        while(num != 0) {
            if (num % 2 != 0) {
                counter++;
            }
            num /= 2;
        }
        return counter;
    }

    vector<int> countBits(int num) {
        vector<int> result;
        for (int i = 0; i <= num; i++) {
            result.push_back(getBinaryOne(i));
        }
        return result;
    }
};

4.2. 相与的方法

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

5. 心得

第一种普通的算法非常容易去想,但是时间复杂度为O(nlogn),第二种算法真的很难想到,时间复杂度为O(n)。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值