0
点赞
收藏
分享

微信扫一扫

剑指 Offer II 003. 前 n 个数字二进制中 1 的个数

小贴贴纸happy 2022-01-21 阅读 108

题目

力扣

思路一 朴素的想法

对每个数字逐个统计二进制位,通过右移实现。

代码一

class Solution {
public:
    vector<int> countBits(int n) {
        vector<int> ans(n+1);
        for(int x=0;x<=n;x++){
            int cnt=0,t=x;
            while(t){
                cnt+=t&1;
                t=t>>1;
            }
            ans[x]=cnt;
        }
        return ans;
    }
};

思路二 lowbit

根据lowbit可以把最右边的1去掉的性质,可以缩短用时。

代码二

class Solution {
public:
    vector<int> countBits(int n) {
        vector<int> ans(n+1);
        for(int x=0;x<=n;x++){
            int cnt=0,t=x;
            while(t){
                cnt++;
                t-=t&(-t);
            }
            ans[x]=cnt;
        }
        return ans;
    }
};

思路三 动态规划

每个数的1的个数是它右移一位的数1的个数+最低位是否为1.

代码三

class Solution {
public:
    vector<int> countBits(int n) {
        vector<int> ans(n+1);
        for(int i=0;i<=n;i++){
            ans[i]=ans[i>>1]+(i&1);
        }
        return ans;
    }
};
举报

相关推荐

0 条评论