AcWing
  • 首页
  • 活动
  • 题库
  • 竞赛
  • 应用
  • 更多
    • 题解
    • 分享
    • 商店
    • 问答
    • 吐槽
  • App
  • 登录/注册

LeetCode 338. 比特位计数

作者: 作者的头像   半醒的狐狸 ,  2023-02-28 11:48:08 ,  所有人可见 ,  阅读 8


0


23.02.28 学习

$O(nlogn)$算法1,暴力统计

class Solution {
public:
    vector<int> res;

    vector<int> countBits(int n) {
        for (int i = 0; i <= n; i ++ ) {
            string num = to2jinzhi(i);
            int cnt = 0;
            for (int j = 0; j < num.size(); j ++ ) {
                if (num[j] == '1') cnt ++ ;
            }
            res.push_back(cnt);
        }

        return res;
    }

    string to2jinzhi(int x) {
        string ans = "";
        int tmp;

        while (x > 0) {
            tmp = x % 2;
            x /= 2;
            ans += to_string(tmp);
        }
        return ans;
    }
};

$O(n)$动态规划

i二进制中1的个数= (右移i-1位)的1个数 + (最后一位 & 1)

class Solution {
public:
    vector<int> countBits(int n) {
        vector<int> f(n + 1);
        for (int i = 1; i <= n; i ++ ) {
            f[i] = f[i >> 1] + (i & 1);
        }

        return f;
    }
};

0 评论

你确定删除吗?
1024
x

© 2018-2023 AcWing 版权所有  |  京ICP备17053197号-1
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标
请输入绑定的邮箱地址
请输入注册信息