338. Counting Bits

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

Follow up:

    • It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
    • Space complexity should be O(n).
    • Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

题目含义:统计二进制数字num以内每个数中‘1’的个数

 

复制代码
 1     
 2     int countbit(int i)
 3     {
 4         //无关trick   i&(i - 1), 这个本来是用来判断一个数是否是2的指数的快捷方法,比如8,二进制位1000, 那么8&(8-1)为0,只要为0就是2的指数
 5 //        按照定义做, x&(x-1)可以消去最右边的1
 6         int count = 0;
 7         while(i>0)
 8         {
 9             i &= (i-1);
10             count ++;
11         }
12         return count;
13     }
14     
15     public int[] countBits(int num) {
16         int[] res = new int[num+1];
17         if (num == 0) return res;
18         res[0] = 0;
19         for (int i=1;i<=num;i++)
20         {
21 //            res[i] = countbit(i);//解法一
22             res[i] = res[i & (i - 1)] + 1;//每个i值都是i&(i-1)对应的值加1
23         }
24         return res;       
25     }
复制代码

 

posted @   daniel456  阅读(141)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示