萌新练习写代码的每日一练:数组异或操作

    科技2022-07-17  128

    给你两个整数,n 和 start 。

    数组 nums 定义为:nums[i] = start + 2*i(下标从 0 开始)且 n == nums.length 。

    请返回 nums 中所有元素按位异或(XOR)后得到的结果。

    输入:n = 5, start = 0 输出:8 解释:数组 nums 为 [0, 2, 4, 6, 8],其中 (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8 。      "^" 为按位异或 XOR 运算符。

    思路:先用一个循环按照定义将值输入到数组nums,之后先将nums[0]赋值给temp,再用循环对数组里的数进行按位异或计算

    代码:

    class Solution:

        def xorOperation(self, n: int, start: int) -> int:

            nums = {}

            for i in range(0, n):

                nums[i] = start + 2*i

            temp = nums[0]

            for i in range(1, n):

                temp = temp ^ nums[i]

            return temp

    学到的新方法:不用nums直接暴力解决

    代码:

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

    这样没用到nums,但依然通过了(有够暴力

    题目来自LeetCode 1486

    Processed: 0.010, SQL: 8