This article is participating in the “Java Theme Month – Java Brush questions punch card”, see the activity link for details

Topic describes

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.

Example 1: Input: n = 5, start = 0 Output: 8 Description: Array nums is [0, 2, 4, 6, 8], where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8. "^" is the bitwise XOR operator. Source: LeetCode Link: https://leetcode-cn.com/problems/xor-operation-in-an-array Copyright belongs to The Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.Copy the code

Thought analysis

  • This question is a simple one, and you can get the correct answer by following the instructions directly.
  • The topic mainly examines the knowledge of bit operation. Bitwise operations are operations based on the binary representation of integers. Since computers store data internally in binary, bit operations are fairly fast.
  • There are six basic bitwise operations, including bitwise and, bitwise or, bitwise xor, bitwise inverse, bitwise left and right. The summary is as follows:

AC code

    public int xorOperation(int n, int start) {
        int ans = 0;
        int[] nums = new int[n];
        for (int i = 0; i < n; i++) {
            ans ^= (start + 2 * i);
        }
        return ans;
    }
Copy the code

conclusion

  • The time complexity of this algorithm is O(n), the space complexity is O(n).
  • Bit operation knowledge needs to memorize, flexible application to master better! We use bit operations less directly in normal development and more in Java common packages.
  • Stick to the daily question, come on!