↓快轉到主要內容
  1. LeetCode/

LeetCode 1486: XOR Operation in an Array

·1 分鐘· ·
LeetCode Easy Math Bit-Manipulation
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2025-12-18

  • 提交紀錄:Accepted(Python)→ Accepted(C++)→ Wrong Answer(C++)→ Accepted(C++)

解題思路
#

第 i 個數是 start + 2 * i,n 最多 1000,直接逐一 XOR 就好。

我的嘗試
#

Python 和 C++ 都一次 AC;之後重寫 C++ 時把 2 * i 打成 n * i。例如 n = 5、start = 0:應該是 0 ^ 2 ^ 4 ^ 6 ^ 8 = 8,這版算的是 0 ^ 5 ^ 10 ^ 15 ^ 20 = 20。

正確解法
#

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

複雜度
#

時間 O(n),空間 O(1)。

要特別避免的錯誤
#

  • 步長是固定的 2,不是 n。

面試口說整理
#

照定義產生每個 start + 2i,用一個變數累積 XOR。n 很小,O(n) 就夠了;要 O(1) 的話可以用 1 ^ 2 ^ ... ^ k 的週期公式。

相關文章

LeetCode 342: Power of Four
·1 分鐘
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 342 解題筆記:先確認是 2 的次方,再確認那個 1 在偶數位:n & 0x55555555 != 0,或 n % 3 == 1
LeetCode 405: Convert a Number to Hexadecimal
·1 分鐘
LeetCode Easy Math String Bit-Manipulation
LeetCode 405 解題筆記:負數先加上 2^32 變成補數,再每次取 4 個位元(% 16)轉成十六進位;0 要特別處理
LeetCode 231: Power of Two
·1 分鐘
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 231 解題筆記:2 的次方只有一個位元是 1,n & (n - 1) 會把最低的 1 消掉,結果是 0 就是;n 要是正數
LeetCode 67: Add Binary
·1 分鐘
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 解題筆記:從兩個字串的尾巴往前逐位相加,進位是 sum // 2,這一位是 sum % 2
LeetCode 1290: Convert Binary Number in a Linked List to Integer
·1 分鐘
LeetCode Easy Linked-List Bit-Manipulation Math
LeetCode 1290 解題筆記:從頭走到尾,每一步把目前的值左移一位再加上新的位元
LeetCode 762: Prime Number of Set Bits in Binary Representation
·1 分鐘
LeetCode Easy Math Bit-Manipulation Primality-Test
LeetCode 762 解題筆記:數字最多 10^6 < 2^20,1 的個數最多 19,直接比對小質數集合