一、數組異或操作(Weekly Contest 194)

題目描述:
給你兩個整數,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

提示:

1 <= n <= 1000
0 <= start <= 1000
n == nums.length

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/xor-operation-in-an-array
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

比較簡單的一道題目:

class Solution {
    public int xorOperation(int n, int start) {
         int res = 0;
        for (int i = 0; i < n ; i++) {
             res = res ^(start + (i << 1));
        }

        return res;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章