1 异或性质介绍
1.1 满足结合律和交换律
a ^ b=b ^ a
a ^ (b ^ c) = (a ^ b) ^ c
1.2 其他特性
(1)对于任何数x,都有x^x=0,x^0=x
(2)如果 a ^ b = c 成立,那么a ^ c = b 与 b ^ c = a 均成立。
即 如果有三个数,满足其中两个数的异或值等于另一个值,那么这三个数的顺序可以任意调换。
注:利用这条性质,可以不使用第 3 个变量而交换两个变量的值。
void swap(int& a, int &b)
{
a=a^b;
b=a^b;
a=a^b;
}
注:异或运算其实就是 二进制下不进位的加法,可利用此性质求解两个数的和。
(3)异或1 的配对性定理:
设a为任意非负偶数,b=a+1,则有 a ^ 1 = b , b ^ 1 = a
1.3 小结
2 题目
2.1 数组中两个数的最大异或值
class Solution {
public:
//链接:https://leetcode-cn.com/problems/maximum-xor-of-two-numbers-in-an-array/solution/li-yong-yi-huo-yun-suan-de-xing-zhi-tan-xin-suan-f/
// 先确定高位,再确定低位(有点贪心算法的意思),才能保证这道题的最大性质
// 一位接着一位去确定这个数位的大小
// 利用性质: a ^ b = c ,则 a ^ c = b,且 b ^ c = a
int findMaximumXOR(vector<int>& nums) {
int res = 0;
int mask = 0;
for (int i = 30; i >= 0; --i)
{
// 注意点1:注意保留前缀的方法,mask 是这样得来的
// 用异或也是可以的 mask = mask ^ (1 << i);
mask = mask | (1 << i);
unordered_set<int> s;
// 这里先假定第 n 位为 1 ,前 n-1 位 res 为之前迭代求得
int temp = res | (1 << i);
for (auto& num : nums)
{
// 注意点2:这里使用 & ,保留前缀的意思(从高位到低位)
int prefix = num & mask;
if (s.count(prefix ^ temp))
{
res = temp;
break;
}
else
{
s.insert(prefix);
}
}
}
return res;
}
};
2.2 不用加减乘除做加法
class Solution {
public:
int add(int a, int b) {
//方法一
//注意: c++不支持负值左移,需要强制转换为无符号数
while(b)
{
int c = (unsigned int)(a&b) << 1;
a ^= b;
b = c;
}
return a;
// 方法二
// return b == 0 ? a : add(a^b, (unsigned int)(a&b) << 1);
}
};
2.3 数组的异或操作
//参考链接:https://leetcode-cn.com/problems/xor-operation-in-an-array/solution/xiao-ming-zuo-shu-xue-by-xiaohu9527-0pu7/
// https://leetcode-cn.com/problems/xor-operation-in-an-array/solution/gong-shui-san-xie-yi-ti-shuang-jie-mo-ni-dggg/
class Solution {
public:
//sumXor(x) = 0^1^2^...^x
int sumXor(int x)
{
if (x % 4 == 0)
{
return x;
}
if (x % 4 == 1)
{
return 1;
}
if (x % 4 == 2)
{
return x + 1;
}
return 0;
}
int xorOperation(int n, int start)
{
int s = start >> 1, e = n & start & 1;
int ret = sumXor(s - 1) ^ sumXor(s + n - 1);
return ret << 1 | e;
}
};
2.4
2.5
2.6
2.7