Welcome to Subscribe On Youtube
3688. Bitwise OR of Even Numbers in an Array
Description
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
Solutions
Solution 1: Simulation
We define a variable $\textit{ans}$ with an initial value of 0. Then, we iterate through each element $x$ in the array $\textit{nums}$; if $x$ is even, we update $\textit{ans}$ with the bitwise OR of $\textit{ans}$ and $x$.
Finally, we return $\textit{ans}$.
The time complexity is $O(n)$, where $n$ is the length of the array $\textit{nums}$. The space complexity is $O(1)$.
-
class Solution { public int evenNumberBitwiseORs(int[] nums) { int ans = 0; for (int x : nums) { if (x % 2 == 0) { ans |= x; } } return ans; } } -
class Solution { public: int evenNumberBitwiseORs(vector<int>& nums) { int ans = 0; for (int x : nums) { if (x % 2 == 0) { ans |= x; } } return ans; } }; -
class Solution: def evenNumberBitwiseORs(self, nums: List[int]) -> int: return reduce(or_, (x for x in nums if x % 2 == 0), 0) -
func evenNumberBitwiseORs(nums []int) (ans int) { for _, x := range nums { if x%2 == 0 { ans |= x } } return } -
function evenNumberBitwiseORs(nums: number[]): number { return nums.reduce((ans, x) => (x % 2 === 0 ? ans | x : ans), 0); }