1486. 数组异或操作 javascript & python
题目:
给你两个整数,n 和 start 。
数组 nums 定义为:nums[i] = start + 2*i(下标从 0 开始)且 n == nums.length 。
请返回 nums 中所有元素按位异或(XOR)后得到的结果。
example:
输入:n = 5, start = 0
输出:8
解释:数组 nums 为 [0, 2, 4, 6, 8],其中 (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8 。
"^" 为按位异或 XOR 运算符。
输入:n = 4, start = 3
输出:8
解释:数组 nums 为 [3, 5, 7, 9],其中 (3 ^ 5 ^ 7 ^ 9) = 8.
输入:n = 1, start = 7
输出:7
输入:n = 10, start = 5
输出:2
思路: javascript & python
- for循环,每次异或值相加返回
代码1
var xorOperation = function(n, start) {
let result = 0;
for(let i=0;i<n;i++){
result ^= start + 2 * i;
}
return result;
};

代码2
class Solution:
def xorOperation(self, n: int, start: int) -> int:
result = 0
for i in range(n):
result ^= start + 2 * i
return result

注:同样都是进行的for循环操作,然后进行异或相加返回,可见python所耗时间和内存消耗就比JS要少。
学艺不精,还需努力💪
本文介绍了一道编程题,要求根据给定的整数n和start,计算数组nums(nums[i]=start+2*i)中所有元素按位异或(XOR)的结果。提供了JavaScript和Python两种语言的解决方案,通过for循环实现异或操作并返回结果。示例展示了不同输入下的输出,并指出Python在时间和内存消耗上优于JavaScript。
500

被折叠的 条评论
为什么被折叠?



