Bitwise OR of Even Numbers in an Array Problem
#3688
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3688.
You are given an integer array nums.
Return the bitwise OR of all even numbers in the array.
If there are no even numbers in nums, return 0.
Example 1:
Input: nums = [1,2,3,4,5,6]
Output: 6
Explanation:
The even numbers are 2, 4, and 6. Their bitwise OR equals 6.
Example 2:
Input: nums = [7,9,11]
Output: 0
Explanation:
There are no even numbers, so the result is 0.
Example 3:
Input: nums = [1,8,16]
Output: 24
Explanation:
The even numbers are 8 and 16. Their bitwise OR equals 24.
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 100
Solution
Approach: Simulation
Start with ans = 0. For each even x in nums, set ans |= x. If there is no even number, the answer stays 0.
Complexity: O(n) time and O(1) extra space, where n is the length of nums.
class Solution:
def evenNumberBitwiseORs(self, nums: List[int]) -> int:
ans = 0
for x in nums:
if x % 2 == 0:
ans |= x
return ans