LC 1486. 數(shù)組異或操作

給你兩個(gè)整數(shù),n 和 start 。
數(shù)組 nums 定義為:nums[i] = start + 2*i(下標(biāo)從 0 開(kāi)始)且 n == nums.length 。
請(qǐng)返回 nums 中所有元素按位異或(XOR)后得到的結(jié)果。

示例 1:
輸入:n = 5, start = 0
輸出:8
解釋?zhuān)簲?shù)組 nums 為 [0, 2, 4, 6, 8],其中(0 ^ 2 ^ 4 ^ 6 ^ 8) = 8 。
"^" 為按位異或 XOR 運(yùn)算符。

示例 2:
輸入:n = 4, start = 3
輸出:8
解釋?zhuān)簲?shù)組 nums 為 [3, 5, 7, 9],其中 (3 ^ 5 ^ 7 ^ 9) = 8.

示例 3:
輸入:n = 1, start = 7
輸出:7

示例 4:
輸入:n = 10, start = 5
輸出:2

Solution:

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

解題:
異或操作,簡(jiǎn)單來(lái)說(shuō)位同為0,不同為1

XOR 1 0
0 1 0
1 0 1

從這里我們看出0和其他位異或都是其他,所以我們?cè)O(shè)初始ans =0,每次將求出來(lái)的值與ans異或迭代并更新ans,直到循環(huán)結(jié)束。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容