当前位置:网站首页>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;
}
};
位运算常用技巧
边栏推荐
- Say good woman programmers do testing have an advantage?More than a dozen interview, abuse of cry ~ ~ by the interviewer
- leetcode括号匹配问题——32.最长有效括号
- [OpenCV from entry to practice] image processing technology [pixel] (the most detailed in the whole network)
- Use the browser's local storage to realize the function of remembering the user name
- Redis集群模式
- leetcode 204. Count Primes 计数质数 (Easy)
- nacos registry
- el-input can only input integers (including positive numbers, negative numbers, 0) or only integers (including positive numbers, negative numbers, 0) and decimals
- Redis(十一) - 异步优化秒杀
- Polar Parametrization for Vision-based Surround-View 3D Detection Paper Notes
猜你喜欢
Navicat cannot connect to mysql super detailed processing method
ATM系统
H5 access payment process - WeChat payment & Alipay payment
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)
51 microcontroller peripherals article: dot-matrix LCD
Polar Parametrization for Vision-based Surround-View 3D Detection Paper Notes
C language: Check for omissions and fill in vacancies (3)
VMTK环境配置记录
goroutine (coroutine) in go language
随机推荐
对node工程进行压力测试与性能分析
pytorch常用函数
【C语言】LeetCode26.删除有序数组中的重复项&&LeetCode88.合并两个有序数组
leetcode括号匹配问题——32.最长有效括号
无代码生产新模式探索
leetcode每天5题-Day04
服务器的单机防御与集群防御
How Navicat Connects to MySQL
聪明人的游戏提高篇:第三章第二课:“桐桐数”(number)
Redis database
面试官:设计“抖音”直播功能测试用例吧
Deep learning - CNN realizes the recognition of MNIST handwritten digits
classSR论文阅读笔记
高防服务器防御的原理是什么
How much does a test environment cost? Start with cost and efficiency
分布式文件存储服务器之Minio对象存储技术参考指南
H5 access payment process - WeChat payment & Alipay payment
点云旋转到参考坐标系方向(最小方向包围盒方法)
Redis集群模式
About the directory structure of the web application