Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit Punch card activity. Click here for details.

I. Problem description

I give you two integers, n and start.

The array nums is defined as: nums[I] = start + 2* I (subscripts start from 0) and n == nums.length.

Return the result of bitwise XOR (XOR) of all elements in NUMS.

Title link: Array xOR operations.

Two, the title requirements

Sample 1

Input: n = 5, start = 0 Output: 8 Explanation: array nums is [0, 2, 4, 6, 8], where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8 "^" is the bitwise XOR operator.Copy the code

The sample 2

Input: n = 4, start = 3 Output: 8 Description: array nums is [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8.Copy the code

inspection

2. It is recommended to take 5 to 20 minutesCopy the code

Third, problem analysis

In this article, you can read more details about bitwise operations:

Day 45: Bit operation

This is essentially a test of the skillful use of the xor algorithm in contraption. For xOR:

** symbol ** : ^ ** Operation rule ** : Two binary bits are opposite 1, the same is 0 ** Example ** : 1001^0111=1110Copy the code

Then we just need to use a simple for loop to evaluate the value of the array, perform xor, and print the result!

Four, coding implementation

class Solution {
public:
    int xorOperation(int n, int start) {
        int i,ans;// Initialize the definition
        vector<int>nums(n+1);// Define a one-dimensional array to store regular values
        for(i=0; i<n; i++)/ / a for loop
        {
            nums[i]=start+2*i;// regular calculation
            if(i==0)
            {
                ans=nums[0];// Assign the initial value
            }
            else
                ans=ans^nums[i];// Xor calculation
                
        }
        return ans;// Output the result}};Copy the code

V. Test results