跳转至

3688. 偶数的按位或运算

题目描述

给你一个整数数组 nums

返回数组中所有 偶数 的按位 运算结果。

如果 nums 中没有偶数,返回 0。

 

示例 1:

输入: nums = [1,2,3,4,5,6]

输出: 6

解释:

偶数为 2、4 和 6。它们的按位或运算结果是 6。

示例 2:

输入: nums = [7,9,11]

输出: 0

解释:

数组中没有偶数,因此结果为 0。

示例 3:

输入: nums = [1,8,16]

输出: 24

解释:

偶数为 8 和 16。它们的按位或运算结果是 24。

 

提示:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100

解法

方法一:模拟

我们定义一个答案变量 \(\textit{ans}\),初始值为 0。然后我们遍历数组 \(\textit{nums}\) 中的每个元素 \(x\),如果 \(x\) 是偶数,则将 \(\textit{ans}\) 更新为 \(\textit{ans}\)\(x\) 的按位或运算结果。

最后返回 \(\textit{ans}\)

时间复杂度 \(O(n)\),其中 \(n\) 是数组 \(\textit{nums}\) 的长度。空间复杂度 \(O(1)\)

1
2
3
class Solution:
    def evenNumberBitwiseORs(self, nums: List[int]) -> int:
        return reduce(or_, (x for x in nums if x % 2 == 0), 0)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
    public int evenNumberBitwiseORs(int[] nums) {
        int ans = 0;
        for (int x : nums) {
            if (x % 2 == 0) {
                ans |= x;
            }
        }
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
public:
    int evenNumberBitwiseORs(vector<int>& nums) {
        int ans = 0;
        for (int x : nums) {
            if (x % 2 == 0) {
                ans |= x;
            }
        }
        return ans;
    }
};
1
2
3
4
5
6
7
8
func evenNumberBitwiseORs(nums []int) (ans int) {
    for _, x := range nums {
        if x%2 == 0 {
            ans |= x
        }
    }
    return
}
1
2
3
function evenNumberBitwiseORs(nums: number[]): number {
    return nums.reduce((ans, x) => (x % 2 === 0 ? ans | x : ans), 0);
}

评论