当前位置:网站首页>338. 比特位计数
338. 比特位计数
2022-07-23 08:03:00 【ATTACH_Fine】
题目
给你一个整数 n ,对于 0 <= i <= n 中的每个 i ,计算其二进制表示中 1 的个数 ,返回一个长度为 n + 1 的数组 ans 作为答案。
示例:
思路
对于所有的数字,只有两类:
**奇数:**二进制表示中,奇数一定比前面那个偶数多一个 1,因为多的就是最低位的 1。
举例:
0 = 0 1 = 1
2 = 10 3 = 11
偶数:二进制表示中,偶数中 1 的个数一定和除以 2 之后的那个数一样多。因为最低位是 0,除以 2 就是右移一位,也就是把那个 0 抹掉而已,所以 1 的个数是不变的。
举例:
2 = 10 4 = 100 8 = 1000
3 = 11 6 = 110 12 = 1100
初始化 dp[0] = 0;
代码
class Solution {
public int[] countBits(int n) {
int[] res = new int[n+1];
res[0] = 0;
for(int i = 1; i <= n; i++){
if((i & 1) != 0) //奇数
res[i] = res[i-1] + 1;
else
res[i] = res[i/2];
}
return res;
}
}
边栏推荐
- FPGA工程师如何进行复杂系统设计?
- Day 5 experiment
- Day108. Shang Yitong: interface docking of hospital simulation system - query of hospital | Department | shift scheduling, addition, deletion, modification and paging conditions
- 使用Stream流来进行分类展示。
- Using redis to realize distributed lock (single redis)
- 测试平台、硬件设计描述
- Head products generated 2.5 billion yuan, and SLG track was also targeted by black products
- 激励发生器、监测器
- 酷睿i7 1165g7相当于什么水平 i71165g7属于哪个档次
- Notes on the ninth day
猜你喜欢

kafka消费报错coordinator unavailable.Rediscovery will be attempt redisCovery

机器学习入门难?说说我是如何快速开始机器学习入门的!

How can Creo 9.0 quickly modify CAD coordinate system?

Day108.尚医通:医院模拟系统接口对接 - 医院|科室|排班 增删改分页条件查询

MySQL enables scheduled task execution

Rtx3080 is equivalent to GTX. What kind of graphics card is rtx3080? What level is rtx3080

酷睿i5 12490f和i5 12600k差距大吗

OSPF details (1)

英特尔赛扬7305性能怎么样?相当于什么水平级别

Surrounded Regions
随机推荐
锐龙R7 PRO 6850H核显性能怎么样?相当于什么水平
强化學習——策略梯度理解點
STM32输出正弦波+cubeMX配置+HAL库
第四天笔记
How many processors is Tianji 1100 equivalent to snapdragon? How about Tianji 1100 equivalent to snapdragon
酷睿i5 12490f和i5 12600k差距大吗
拖拽----
iQOO 10 Pro和vivo X80 Pro区别 哪个好详细参数配置对比
第十天笔记
设计例化和连接
Renforcement de l'apprentissage - points de compréhension du gradient stratégique
UIScrollView(UICollectionView)禁止横向和竖向同时滑动
第五天笔记
Head products generated 2.5 billion yuan, and SLG track was also targeted by black products
PyTorch到底好用在哪里?
Detailed introduction of RIP
Static comprehensive experiment (HCIA)
数据库连接池 & DBUtils
使用Stream流来进行分类展示。
Comparison of iqoo 10 pro and Xiaomi 12 ultra configurations