当前位置:网站首页>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;
}
}
边栏推荐
- What level is the notebook core i5 1135g7 equivalent to? How about i5 1135g7 performance
- What level is rtx3090ti? What level is rtx3090ti graphics card? How about rtx3090ti graphics card
- pingbanceshi
- overlayfs源代码解析
- MGRE comprehensive experiment
- How about the performance of Ruilong R7 Pro 5875u? What level is it equivalent to
- js 实现 encode64 加密
- What is Tianji 920 equivalent to a snapdragon? How much is Tianji 920 equivalent to a snapdragon? How about Tianji 920
- FPGA工程师如何进行复杂系统设计?
- Detailed explanation of knapsack problem
猜你喜欢
随机推荐
中等靶场
Design instantiation and connection
容器网络原理
Static comprehensive experiment (HCIA)
第七天笔记
pingbanceshi
Reinforcement learning -- understanding point of strategy gradient
接口interface
Detailed explanation of knapsack problem
强化学习——策略梯度理解点
拖拽----
What's the difference between core i9 12950hx and i9 12900hx
Renforcement de l'apprentissage - points de compréhension du gradient stratégique
rtx3080ti和rtx3080差距 3080和3080ti参数对比
Rtx3080 is equivalent to GTX. What kind of graphics card is rtx3080? What level is rtx3080
Fastadmin changes the pop-up size of the default table button
rtx3090ti什么水平 rtx3090ti显卡什么级别 rtx3090ti显卡怎么样
英特尔赛扬7300性能怎么样?相当于什么水平级别
第六天笔记
What level is rtx3090ti? What level is rtx3090ti graphics card? How about rtx3090ti graphics card








