求0~n里面每个数二进制1的个数,用o(n)算法

338. Counting Bits

    My Submissions
Total Accepted: 20178  Total Submissions: 36151  Difficulty: Medium

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].









clclass Solution {
public:
vector<int> countBits(int num) {
       vector<int>ans;
       ans.push_back(0);
       int res=0;
       for(int i=1;i<=num;i++)
       {
           if((i&(i-1))==0) 
               {
                   res=i;
                   ans.push_back(1);
               }
           else 
           {
               ans.push_back(ans[i-res]+1);
           }
       }
       return ans;
   }
};


上一篇: 求二叉搜索树中第k个节点
下一篇: 链表反转 递归写法
左眼皮跳跳~
博客等级 码龄13年 17粉丝 400原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值