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 }
分类:
leetcode_dp
, leetcode_bit
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!