Leetcode 338. 比特位计数

Leetcode 338. 比特位计数

1、问题分析

题目链接:https://leetcode-cn.com/problems/counting-bits/
  暴力破解法。代码我已经进行了详细的注释,理解应该没有问题,读者可以作为参考,如果看不懂(可以多看几遍),欢迎留言哦!我看到会解答一下。

2、问题解决

  笔者以C++方式解决。

#include "iostream"

using namespace std;

#include "algorithm"
#include "vector"
#include "queue"
#include "set"
#include "map"
#include "string"
#include "stack"

class Solution {
private:
    // 结果数组
    vector<int> resultChen;
public:
    vector<int> countBits(int num) {
        dealChen(num);
        return resultChen;
    }

    void dealChen(int number) {
        // 依次计算每个数值
        for (int i = 0; i <= number; ++i) {
            // 初始化 1 的数量为 0
            int num = 0;
            // 正在计算的数
            int result = i;
            while (result > 0) {
                // 遇到 1 则个数 +1
                if (result % 2 == 1) {
                    num++;
                }
                // 不断缩小 result 值
                result /= 2;
            }
            // 保存结果
            resultChen.push_back(num);
        }
    }
};

int main() {

    Solution *pSolution = new Solution;
    auto vector1 = pSolution->countBits(2);
    for (int i = 0; i < vector1.size(); ++i) {
        cout << vector1[i] << " ";
    }
    cout << endl;


    system("pause");
    return 0;
}

运行结果

在这里插入图片描述
有点菜,有时间再优化一下。

3、总结

  难得有时间刷一波LeetCode, 这次做一个系统的记录,等以后复习的时候可以有章可循,同时也期待各位读者给出的建议。算法真的是一个照妖镜,原来感觉自己也还行吧,但是算法分分钟教你做人。前人栽树,后人乘凉。在学习算法的过程中,看了前辈的成果,受益匪浅。
感谢各位前辈的辛勤付出,让我们少走了很多的弯路!
哪怕只有一个人从我的博客受益,我也知足了。
点个赞再走呗!欢迎留言哦!

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值