当前位置:网站首页>leetcode_191_2021-10-15
leetcode_191_2021-10-15
2022-06-24 19:25:00 【programing菜鸟】
这是一道很简单的题目,这里我要介绍对它的优化解题方案。
法一:
直接遍历32位,利用位运算找到有1的位,然后利用oneNums来维护。
class Solution {
public:
int hammingWeight(uint32_t n) {
int oneNums = 0;
for(int i = 0; i < 32; ++i){
//直接遍历n的每一位
if((n >> i) & 1) //如果该位为1
oneNums++;
}
return oneNums;
}
};
法二:
这是一种最直接也是最简单的方法,它的时间复杂度是O(N) (虽然是遍历32次,可以当作O(1),但是为了和下面的方法区分,这里认为是O(N)),空间复杂度是O(1)。
我们还有优化方案。
这里要介绍一个小技巧,Brian Kernighan 算法。利用n & (n - 1)会将n的最后一位1变成0.利用这个技巧,我们只需要不断的n & n-1,直到n等于0。而这里n变成0所经历的次数就是1的个数.
class Solution {
public:
int hammingWeight(uint32_t n) {
// 法二: 利用n & (n - 1) 会将n的最后一位1变成0
int oneNums = 0;
while(n){
n &= n - 1; //消除一位0,直到n == 0
oneNums++;
}
return oneNums;
}
};
时间复杂度是O(K),K是n中为1的个数。空间复杂度为O(1)。
而我们还有更高级的方法。
法三:
这种方法类似于二分法,二进制中的每一位都没有别的含义。而我们要做的就是赋予每一位别的含义:二进制中的每一位都代表1个计数器,而我们要做的就是想方设法把这些计数器加起来,这就是我们的答案。
- 解释:
考虑3这个无符号整数,3的二进制序列有多少个1呢?
基于这个想法,就有了下面这种方法。
class Solution {
public:
int hammingWeight(uint32_t n) {
//法三:将每一位看作计数器
n = (n & 0x55555555) + ((n >> 1) & 0x55555555);
n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
n = (n & 0xf0f0f0f) + ((n >> 4) & 0xf0f0f0f);
n = (n & 0xff00ff) + ((n >> 8) & 0xff00ff);
n = (n & 0xffff) + ((n >> 16) & 0xffff);
return n;
}
};
- 你可能完全不懂这段代码在干什么,别急。我们来看看这些数字的特征。

n & 0x55555555 就是统计出每隔两位的低位的1的个数。
(n >> 1) & 0x55555555 就是统计出每隔两位的高位的1的个数。
相加就得到了每隔两位中1的个数。
然后n & 0x33333333 就是统计每隔4位中低两位中的1的个数。
(n >> 2) & 0x33333333就是统计出每隔4位中高两位中的1的个数。
剩下的同理即可。
时间复杂度为O(1),空间复杂度也是O(1)。
法四:(娱乐法)
这种方法是我在一本书中发现的,使用的手法是模板元编程。只不过不能用于这道题,纯粹娱乐。
template<int N>
struct OneInBinary {
enum {
value = N % 2 + OneInBinary<N/2>::value };
};
template<>
struct OneInBinary<0> {
enum {
value = 0};
};
//调用方法
OneInBinary<45>::value;
边栏推荐
- Alibaba cloud schedules tasks and automatically releases them
- Graduation summary of phase 6 of the construction practice camp
- Auto. JS to automatically authorize screen capture permission
- Codeforces Round #720 (Div. 2)
- Blender's simple skills - array, rotation, array and curve
- Shengzhe technology AI intelligent drowning prevention service launched
- Tdengine can read and write through dataX
- Multi view function in blender
- PKI notes
- database/sql
猜你喜欢

关于Unity中的transform.InverseTransformPoint, transform.InverseTransofrmDirection

去掉录屏提醒(七牛云demo)

Pattern recognition - 9 Decision tree

188. the best time to buy and sell stocks IV

VSCode无网环境快速迁移开发环境(VIP典藏版)

Network flow 24 questions (round table questions)

【Camera基础(二)】摄像头驱动原理和开发&&V4L2子系统驱动架构

Intelligent fish tank control system based on STM32 under Internet of things

Docking of arkit and character creator animation curves

Antdb database online training has started! More flexible, professional and rich
随机推荐
PHP script calls command to get real-time output
Decoration home page custom full screen video playback effect GIF dynamic picture production video tutorial playback code operation settings full screen center Alibaba international station
Web project deployment
[cloud native learning notes] kubernetes Foundation
(to be optimized and modified) vivado DDR4 SDRAM (MIG) (2.2) IP core learning record
#国企央企结构化面试#国企就业#墨斗互动就业服务管家
database/sql
Wireshark packet capturing skills summarized by myself
Advanced secret of xtransfer technology newcomers: the treasure you can't miss mentor
Tso hardware sharding is a header copy problem
一文理解OpenStack网络
Introduction to interval DP
Remember the frequently forgotten problem of continuously reading pictures -%04d
Three more days
123. 买卖股票的最佳时机 III
力扣每日一题-第25天-496.下一个更大元素Ⅰ
Jar package operation
Page replacement of virtual memory paging mechanism
Golang daily question
ping: www.baidu. Com: unknown name or service