Difficulty: 🟢 Easy
You are given an integer n
and an integer start
.
Define an array nums
where nums[i] = start + 2 * i
(0-indexed) and n == nums.length
.
Return the bitwise XOR of all elements of nums
.
Example 1:
Input: n = 5, start = 0
Output: 8
Explanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.
Where "^" corresponds to bitwise XOR operator.
Example 2:
Input: n = 4, start = 3
Output: 8
Explanation: Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8.
1 <= n <= 1000
0 <= start <= 1000
n == nums.length
class Solution:
def xorOperation(self, n: int, start: int) -> int:
result = start
for i in range(1, n):
result ^= start + 2 * i
return result
The given solution calculates the bitwise XOR of the elements in the nums
array by iteratively performing XOR operations.
The algorithm works as follows:
- Initialize a variable
result
with the value ofstart
. This variable will store the cumulative XOR of the elements. - Iterate through the range from 1 to
n
, representing the indices of thenums
array.- Calculate the value of
nums[i]
asstart + 2 * i
. - Perform a bitwise XOR operation between
result
andnums[i]
, and updateresult
with the XOR result.
- Calculate the value of
- Return the value of
result
, which represents the bitwise XOR of all the elements in thenums
array.
The algorithm calculates the XOR of each element in the nums
array and updates the cumulative XOR result stored in the result
variable.
The time complexity of this algorithm is O(n), where n is the value of n
. The algorithm iterates through the range from 1 to n
and performs a constant-time XOR operation at each iteration.
The space complexity of the algorithm is O(1) as it uses only a constant amount of extra space to store the result
variable.
The given solution calculates the bitwise XOR of the elements in the nums
array based on the given n
and start
values. It has a time complexity of O(n) and a space complexity of O(1), making it an efficient solution for the problem at hand.
NB: If you want to get community points please suggest solutions in other languages as merge requests.