給你兩個整數,n 和 start 。
數組 nums 定義為:nums[i] = start + 2*i(下標從 0 開始)且 n == nums.length 。
請返回 nums 中所有元素按位異或(XOR)后得到的結果。
示例 1:
輸入:n = 5, start = 0
輸出:8
解釋:數組 nums 為 [0, 2, 4, 6, 8],其中 (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8 。
“^” 為按位異或 XOR 運算符。
示例 2:
輸入:n = 4, start = 3
輸出:8
解釋:數組 nums 為 [3, 5, 7, 9],其中 (3 ^ 5 ^ 7 ^ 9) = 8.
示例 3:
輸入:n = 1, start = 7
輸出:7
示例 4:
輸入:n = 10, start = 5
輸出:2
解題思路
按照數組 nums 的定義:nums[i] = start + 2*i,nums[i]只和start和i有關,因此只需要一個變量存儲結果,每次都與計算的num[i]做異或操作即可。
代碼
func xorOperation(n int, start int) int {res := startfor i := 1; i < n; i++ {res^=start+i*2}return res
}