【leetcode】位运算刷题记录
文章目录
前言
本文是基于leetcode位运算例题的学习记录
LCR 133. 位 1 的个数
链接
两种方法都是很常见的位运算,记忆一下
class Solution {
public:
int hammingWeight(uint32_t n) {
int ans = 0;
while(n != 0)
{
if(n & 1) ans ++;
n >>= 1;
}
return ans;
}
};
class Solution {
public:
int hammingWeight(uint32_t n) {
int res = 0;
while(n != 0)
{
res ++;
n &= n - 1;
}
return res;
}
};
LCR 134. Pow(x, n)
链接
模板题,值得一提的是,n的值得给long变量,否则会发生溢出
class Solution {
public:
double myPow(double x, int n) {
if(x == 0.0f)return 0.0;
long b = n;
double res = 1.0;
if(b < 0)
{
x = 1 / x;
b = -b;
}
while(b > 0)
{
if(b & 1)res *= x;
x *= x;
b >>= 1;
}
return res;
}
};
LCR 177. 撞色搭配
链接
没写出来,知道要用异或运算但是不记得怎么把x和y分开了,枯
题解中这张图应该能很好解释了:
class Solution {
public:
vector<int> sockCollocation(vector<int>& sockets) {
int x = 0, y = 0, n = 0, m = 1;
for(int num : sockets) // 1. 遍历异或
n ^= num;
while((n & m) == 0) // 2. 循环左移,计算 m
m <<= 1;
for(int num : sockets) { // 3. 遍历 sockets 分组
if(num & m) x ^= num; // 4. 当 num & m != 0
else y ^= num; // 4. 当 num & m == 0
}
return vector<int> {x, y}; // 5. 返回出现一次的数字
}
};
作者:Krahets
链接:https://leetcode.cn/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/solutions/572857/jian-zhi-offer-56-i-shu-zu-zhong-shu-zi-tykom/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
LCR 178. 训练计划 VI
class Solution {
public:
int trainingPlan(vector<int>& actions) {
unsigned int bit = 1 << 31;
int res = 0;
for(int i = 31; i >= 0; i -- )
{
int bitSum = 0;
for(auto num:actions)
{
if(num & bit)bitSum ++;
}
res += (bitSum % 3) << i;
bit >>= 1;
}
return res;
}
};
LCR 190. 加密运算
皮一下~
class Solution {
public:
int encryptionCalculate(int dataA, int dataB) {
return dataA + dataB;
}
};
class Solution {
public:
int encryptionCalculate(int dataA, int dataB) {
while(dataB)
{
int dataC = (dataB & dataA) << 1;
dataA ^= dataB;
dataB = dataC;
}
return dataA;
}
};