当前位置:网站首页>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;
}
};
位运算常用技巧

边栏推荐
- Integrate ssm (1)
- 51单片机外设篇:ADC
- C语言小游戏——扫雷小游戏
- leetcode 665. Non-decreasing Array 非递减数列(中等)
- 使用TinkerPop框架对GDB增删改查
- How H5 realizes evoking APP
- 驱动页面性能优化的3个有效策略
- 面试官:设计“抖音”直播功能测试用例吧
- Double for loop case (use js jiujiu printing multiplication table)
- The virtual reality real estate display system foresees the future decoration effect in advance
猜你喜欢

A list of 300+ learning resources compiled by senior engineers of the Tao Department (the latest version in 2021)

The advantages of making web3d dynamic product display

Cyber Security Learning - Intranet Penetration 4

nacos registry

Browser onload event

Redis-cluster mode (master-slave replication mode, sentinel mode, clustering mode)

5款经典代码阅读器的使用方案对比

分布式文件存储服务器之Minio对象存储技术参考指南

Double for loop case (use js jiujiu printing multiplication table)

BGP experiment (route reflector, federation, route optimization)
随机推荐
5款经典代码阅读器的使用方案对比
eggjs controller层调用controller层解决方案
Detailed installation and configuration of golang environment
How much does a test environment cost? Start with cost and efficiency
回文串求解的进阶方法
卸载redis
关于 VS Code 优化启动性能的实践
Shell 脚本不同玩法
An advanced method for solving palindromes
网安学习-内网渗透4
51单片机外设篇:点阵式LCD
51单片机外设篇:DS18B20
The Go language learning notes - dealing with timeout - use the language from scratch from Context
165.比较版本号
Redis(十二) - Redis消息队列
Alluxio为Presto赋能跨云的自助服务能力
What is the most important ability of a programmer?
测试技术之APP蓝牙连接测试
Meta公司内部项目-RaptorX:将Presto性能提升10倍
Block elements, inline elements (
elements, span elements)