当前位置:网站首页>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;
}
};
位运算常用技巧
边栏推荐
- How much does a test environment cost? Start with cost and efficiency
- golang's time package: methods for time interval formatting and output of timestamp formats such as seconds, milliseconds, and nanoseconds
- 面试官:设计“抖音”直播功能测试用例吧
- Meta公司内部项目-RaptorX:将Presto性能提升10倍
- PIL与numpy格式之间的转换
- The advantages of making web3d dynamic product display
- Shell 脚本不同玩法
- 关于 VS Code 优化启动性能的实践
- 测试环境要多少?从成本与效率说起
- leetcode 665. Non-decreasing Array 非递减数列(中等)
猜你喜欢
Thread Basics (1)
H5 access payment process - WeChat payment & Alipay payment
对node工程进行压力测试与性能分析
Point Density-Aware Voxels for LiDAR 3D Object Detection 论文笔记
Introduction to coredns
Alluxio为Presto赋能跨云的自助服务能力
About the directory structure of the web application
eggjs controller层调用controller层解决方案
跨桌面端Web容器演进
BGP实验(路由反射器,联邦,路由优化)
随机推荐
Navicat cannot connect to mysql super detailed processing method
There are more and more talents in software testing. Why are people still reluctant to take the road of software testing?
el-input can only input integers (including positive numbers, negative numbers, 0) or only integers (including positive numbers, negative numbers, 0) and decimals
APP Bluetooth connection test of test technology
6W+字记录实验全过程 | 探索Alluxio经济化数据存储策略
Packaging and deployment of go projects
21 Day Learning Challenge Schedule
机器学习——支持向量机原理
Shell 脚本不同玩法
Redis(十一) - 异步优化秒杀
The advantages of making web3d dynamic product display
Thread Basics (1)
eggjs controller层调用controller层解决方案
配合蓝牙打印的encoding-indexes.js文件内容:
服务器的单机防御与集群防御
Deep learning - CNN realizes the recognition of MNIST handwritten digits
[C language] LeetCode26. Delete duplicates in an ordered array && LeetCode88. Merge two ordered arrays
提高软件测试能力的方法有哪些?看完这篇文章让你提升一个档次
Block elements, inline elements (
elements, span elements)golang's time package: methods for time interval formatting and output of timestamp formats such as seconds, milliseconds, and nanoseconds