目录
解析

136. 只出现一次的数字

题解
class Solution {
public:
int singleNumber(vector<int>& nums) {
// 34.专题五_位运算_常见位运算总结(包含5道算法题)1
int ret = 0;
for (int x : nums) ret ^= x;
return ret;
}
};
260. 只出现一次的数字 III

题解
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
// 34.专题五_位运算_常见位运算总结(包含5道算法题)2
int xorsum = 0;
for (int x : nums) xorsum ^= x;
// 防止溢出
int right_one = (xorsum == INT_MIN ? xorsum : xorsum & (-xorsum)); // 取到最右边的一个1,用于将数组分为两类
int type1 = 0, type2 = 0;
for (int x : nums)
{
if (x & right_one) // 一类该bit位为1,另一类为0
type1 ^= x;
else
type2 ^= x;
}
return {type1, type2};
}
};
191. 位1的个数

题解
class Solution {
public:
int hammingWeight(int n) {
// 34.专题五_位运算_常见位运算总结(包含5道算法题)3
int ret = 0;
while (n)
{
if (n & 1) ret++;
n >>= 1;
}
return ret;
}
};
338. 比特位计数
题解
class Solution {
public:
int hammingWeight(int n) {
// 34.专题五_位运算_常见位运算总结(包含5道算法题)3
int ret = 0;
while (n)
{
if (n & 1) ret++;
n >>= 1;
}
return ret;
}
vector<int> countBits(int n) {
// 34.专题五_位运算_常见位运算总结(包含5道算法题)4
vector<int> ret;
for (int i = 0; i <= n; ++i)
ret.push_back(hammingWeight(i));
return ret;
}
};
461. 汉明距离
题解
class Solution {
public:
int hammingDistance(int x, int y) {
// 34.专题五_位运算_常见位运算总结(包含5道算法题)5
int sox = x ^ y, ret = 0;
while (sox)
{
ret += sox & 1;
sox >>= 1;
}
return ret;
}
};
173

被折叠的 条评论
为什么被折叠?



