浅谈 数组异或操作 问题

数组异或操作

问题:
给你两个整数,n 和 start 。
数组 nums 定义为:nums[i] = start + 2*i(下标从 0 开始)且 n == nums.length
请返回 nums 中所有元素按位异或(XOR)后得到的结果。

思路:
虽然题目中提到了数组,但是针对本题完全没必要申请数组浪费内存。
很简单,按位取异或值就行了。

class Solution {
    
    
public:
    const int xorOperation(const int& n, const int& start) {
    
    
        auto res = 0;
        for(auto i = 0; i < n; ++i){
    
    
            res ^= start + 2 * i;
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_48033173/article/details/112688022