LeetCode 1486. 数组异或操作

给你两个整数,n 和 start 。

数组 nums 定义为:nums[i] = start + 2*i(下标从 0 开始)且 n == nums.length 。

请返回 nums 中所有元素按位异或(XOR)后得到的结果。

输入:n = 5, start = 0
输出:8 解释:数组 nums 为 [0, 2, 4, 6, 8],其中 (0 ^ 2 ^ 4 ^
6 ^ 8) = 8 。
“^” 为按位异或 XOR 运算符。

解法一:模拟

class Solution {
public:
    int xorOperation(int n, int start) {
        int nums[1005] = {0};
        int res = 0;
        for (int i = 0; i < n; i++){
            nums[i] = start + 2 * i;
            res = res ^ nums[i]; 
        }
        return res;
    }
};

解法二:数学

异或的公式

  1. x ^ x = 0;
  2. x ^ y = y ^ x; 交换律
  3. (x ^ y) ^ z = x ^ (y ^ z); 结合律
  4. x ^ x ^ y = y; 自反律
  5. 4i ^ (4i + 1) ^ (4i + 2) ^ (4i + 3) = 0;

本题中需要计算start ^ (start + 2) ^ (start + 4) ^ (start + 6) ^ … ^
(start + 2(n- 1));

注意到如果将上式除2可得start/2 ^ (start/2 + i) ^ (start/2 + 2i) ^ (start/2 + 3i) ^ … ^ (start/2 + (n- 1));
因为异或是位操作,所以将每个值右移1位再进行异或对这部分位并无影响,而原式与新式的关系也易得
原式 = 新式 << 1 | e (e为原式的最低位)
因为原式的每个数要么全为奇数要么全为偶数,所以若e为1则必有n且start为奇数
所以e = start & n & 1;

class Solution {
public:
    int xorOperation(int n, int start) {
        int s = start>>1; 
        int e = n & start & 1;
        int res = SumXor(s - 1) ^ SumXor(s + n -1);
        return res<<1 | e;
    }
    int SumXor(int x){
        if (x % 4 == 0) return x;
        else if (x % 4 == 1) return 1;
        else if (x % 4 == 2) return x + 1;
        return 0;
    }
};

int res = SumXor(s - 1) ^ SumXor(s + n -1);


>  根据定理有相邻的四个数异或结果为 0>  4i ⊕ (4i + 1)(4i + 2)(4i + 3) = 0,而我们要求
> (s^ (s+1) ^ (s+2) ^ …… ^ (s+n-1)) * 2 + e 由定理有
>  x ⊕ x ⊕ y = y,即(s ^(s+1) ^ (s+2) ^ …… ^ (s+n-1)) =1 ^ 2 ^ 3 ^ …… ^ s - 1)(1 ^ 2 ^ 3 ^…… ^ s - 1 ^ s ^ (s+1) ^ (s+2) ^ …… ^ (s+n-1));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值