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

LeetCode 3688: Bitwise OR of Even Numbers in an Array

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

基本資料
#

難易度: easy 第一次嘗試:2025-09-21

  • 提交紀錄:Accepted(一次通過)

解題思路
#

偶數的最低位是 0,挑出來全部 OR 起來(Bit Manipulation 模板一)。OR 的初始值是 0,沒有偶數時不會被改到,剛好就是題目要的 0。

我的解法
#

class Solution:
    def evenNumberBitwiseORs(self, nums: List[int]) -> int:
        res = 0
        for x in nums:
            if x % 2 == 0:
                res |= x
        return res

我當時先過濾、再特判空的情況;初始值用 0 就不需要特判。

複雜度
#

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

要特別避免的錯誤
#

  • OR 的單位元素是 0,AND 的是 -1,不要用錯。

面試口說整理
#

我只對偶數做 OR,初始值 0;沒有偶數時結果自然是 0。時間 O(n)。

相關文章

LeetCode 1920: Build Array from Permutation
·1 分鐘
LeetCode Easy Array Simulation
LeetCode 1920 解題筆記:照定義 ans[i] = nums[nums[i]];要 O(1) 額外空間時,把新值乘 n 疊在原本的值上
LeetCode 3507: Minimum Pair Removal to Sort Array I
·1 分鐘
LeetCode Easy Simulation Array
LeetCode 3507 解題筆記:n 很小直接模擬,切片賦值右邊要是 list
LeetCode 3069: Distribute Elements Into Two Arrays I
·1 分鐘
LeetCode Easy Array Two-Pointers Simulation
LeetCode 3069 解題筆記:照規則模擬:前兩個各放一邊,之後比較兩個陣列的最後一個,放到最後一個比較大的那邊
LeetCode 2859: Sum of Values at Indices With K Set Bits
·1 分鐘
LeetCode Easy Array Bit-Manipulation
LeetCode 2859 解題筆記:看的是 index 的二進位有幾個 1,不是值
LeetCode 682: Baseball Game
·1 分鐘
LeetCode Easy Array Stack Simulation
LeetCode 682 解題筆記:用 stack 存有效的分數,C 刪掉最後一個,D 加入兩倍,+ 加入最後兩個的和
LeetCode 136: Single Number
·1 分鐘
LeetCode Easy Array Bit-Manipulation
LeetCode 136 解題筆記:x ^ x = 0、x ^ 0 = x,把所有數 XOR 起來,出現兩次的互相抵消,剩下的就是答案