leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

commit 2d4d6db5843b264b91ceec6dbb179e6050fd1e74
parent 132e2dca4c2cd33e3e8a4385c6e247ad1221947b
Author: Jack Sangdahl <jack@pngu.org>
Date:   Fri, 26 Dec 2025 20:57:53 -0700

1486. xor operation in an array

Diffstat:
Axor_op_in_arr.c | 34++++++++++++++++++++++++++++++++++
Axor_op_in_arr.py | 27+++++++++++++++++++++++++++
2 files changed, 61 insertions(+), 0 deletions(-)

diff --git a/xor_op_in_arr.c b/xor_op_in_arr.c @@ -0,0 +1,34 @@ +// 1486. XOR Operation in an Array +#include "leetcode.h" + +/* + * you are given an integer 'n' and an integer 'start'. define an array 'nums' + * where 'nums[i] = star + 2 * i' and 'n == nums.length'. return bitwise xor of + * all elements of 'nums'. + */ + +int xor_b(int n, int start) { + if (!(n % 2)) + return (n / 2) & 1; + else + return ((n / 2) & 1) ^ (start + n - 1); +} + +int xor_a(int n, int start) { + if (start & 1) + return (start - 1) ^ xor_b(n + 1, start - 1); + else + return xor_b(n, start); +} + +int xorOperation(int n, int start) { + int ans = 2 * xor_a(n, start / 2); + if (n & start & 1) + ans++; + return ans; +} + +int main() { + printf("%d\n", xorOperation(5, 0)); // expect: 8 + printf("%d\n", xorOperation(4, 3)); // expect: 8 +} diff --git a/xor_op_in_arr.py b/xor_op_in_arr.py @@ -0,0 +1,27 @@ +# 1486. XOR Operation in an Array + +""" +you are given an integer 'n' and an integer 'start'. define an array 'nums' +where 'nums[i] = star + 2 i' and 'n == nums.length'. return bitwise xor of +all elements of 'nums'. +""" + + +class Solution(object): + def xorOperation(self, n, start): + """ + :type n: int + :type start: int + :rtype: int + """ + ans = 0 + nums = [start + i * 2 for i in range(n)] + for i in nums: + ans ^= i + return ans + + +if __name__ == "__main__": + obj = Solution() + print(obj.xorOperation(n=5, start=0)) + print(obj.xorOperation(n=4, start=3))