当前位置:网站首页>leetcode-338.比特位计数
leetcode-338.比特位计数
2022-08-02 05:15:00 【KGundam】
位运算
题目详情
给你一个整数 n ,对于 0 <= i <= n 中的每个 i ,计算其二进制表示中 1 的个数 ,返回一个长度为 n + 1 的数组 ans 作为答案。
示例1:
输入:n = 2
输出:[0,1,1]
解释:
0 --> 0
1 --> 1
2 --> 10
示例2:
输入:n = 5
输出:[0,1,1,2,1,2]
解释:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
思路:
本题利用动态规划+位运算求解
dp[i]表示数字i的二进制含有1的数量
对于0~n这些连续的数字,它们的二进制表示的是…0 …1 …0 …1 末位是01交替的
对于i这个数字,如果它二进制的末位是1,那么说明i-1这个数字比i少一个1
所以dp[i] = dp[i-1] + 1
如果i这个数字末位是0,说明它末位进位了,i-1末位是1
但是我们还不知道前面的情况,比如3和4
0011 0100这种情况i反倒比i-1少一个1,那么我们不能简单地利用
i和i-1之间的关系判断,我们对于这种情况可以利用算术右移
i>>1一定比i小,所以dp[i>>1]一定已经计算过了,所以可以利用它来更新dp
所以本题的关键就是找到比i更小的一个值,来更新dp[i]
所以我们也可以利用i&(i-1)这个更小的值来更新
我的代码:
class Solution
{
public:
vector<int> countBits(int n)
{
vector<int> dp(n + 1, 0);
for (int i = 1; i <= n; ++i)
{
//i&1判断末位是否为1,如果是就↓,如果不是就和dp[i>>1]数量一样
dp[i] = i & 1? dp[i-1] + 1 : dp[i>>1];
//等价于dp[i] = dp[i&(i-1)] + 1;
/*在这个式子里,i&(i-1)将i中最低位的1给去除了 不管去除的是末位还是更高位的1,这个值都比i小(dp存在) 我们再把去除的1加回来即可 */
}
return dp;
}
};
位运算常用技巧

边栏推荐
- Cyber Security Learning - Intranet Penetration 4
- 腾讯大咖分享 | 腾讯Alluxio(DOP)在金融场景的落地与优化实践
- How H5 realizes evoking APP
- 51单片机外设篇:点阵式LCD
- Detailed explanation of interface in Go language
- [PSQL] window function, GROUPING operator
- flex布局(弹性布局)
- Smart people's game improvement: Chapter 3, Lesson 2: "Number of Tongtong" (number)
- 6W+字记录实验全过程 | 探索Alluxio经济化数据存储策略
- 【解决】RESP.app 连接不上redis
猜你喜欢

Google notes cut hidden plug-in installation impression

如何优化OpenSumi终端性能?

OAuth 授权协议 | 都云原生时代了,我们应该多懂一点OAuth ?

5年在职经验之谈:2年功能测试、3年自动化测试,从入门到不可自拔...

Meta公司新探索 | 利用Alluxio数据缓存降低Presto延迟

Use the browser's local storage to realize the function of remembering the user name

目标检测重要概念——IOU、感受野、空洞卷积、mAP

goroutine (coroutine) in go language

机器学习——支持向量机原理

Features and installation of non-relational database MongoDB
随机推荐
复盘:图像饱和度计算公式和图像信噪(PSNR)比计算公式
flex layout (flexible layout)
Polar Parametrization for Vision-based Surround-View 3D Detection 论文笔记
线程基础(一)
机器学习——支持向量机原理
Cyber Security Learning - Intranet Penetration 4
51单片机外设篇:DS18B20
CPU使用率和负载区别及分析
上海交大牵手淘宝成立媒体计算实验室:推动视频超分等关键技术发展
Contents of encoding-indexes.js file printed with Bluetooth:
Use the browser's local storage to realize the function of remembering the user name
测试技术之APP蓝牙连接测试
Alluxio为Presto赋能跨云的自助服务能力
Three methods of importing sql files in MySQL
Mysql implements optimistic locking
Review: image saturation calculation formula and image signal-to-noise (PSNR) ratio calculation formula
LeetCode brush topic series - 787 K station transfer within the cheapest flight
Home NAS server (4) | MergerFS and SnapRaid data backup
5款经典代码阅读器的使用方案对比
PIL与numpy格式之间的转换