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.
1 <= nums.length <= 10000 <= nums[i] <= 1000Iterate through the array and perform bitwise OR operation on all even numbers found.
Algorithm:
result = 0num % 2 == 0), perform bitwise OR with resultThis approach works because:
Example 1: nums = [1, 2, 3, 4, 5, 6]
Step-by-step execution:
| num = 2 (even), result = 0 | 2 = 2 (binary: 0010) |
| num = 4 (even), result = 2 | 4 = 6 (binary: 0110) |
| num = 6 (even), result = 6 | 6 = 6 (binary: 0110) |
Result: 6
Example 2: nums = [1, 3, 5]
Step-by-step execution:
Result: 0 (no even numbers)
Example 3: nums = [2, 4, 6, 8]
Step-by-step execution:
| num = 2 (even), result = 0 | 2 = 2 |
| num = 4 (even), result = 2 | 4 = 6 |
| num = 6 (even), result = 6 | 6 = 6 |
| num = 8 (even), result = 6 | 8 = 14 (binary: 1110) |
Result: 14
class Solution {
public int evenNumberBitwiseORs(int[] nums) {
int res = 0;
for (int num : nums) {
if (num % 2 == 0) {
res |= num;
}
}
return res;
}
}
class Solution {
public int evenNumberBitwiseORs(int[] nums) {
int result = 0;
for (int num : nums) {
if (num % 2 == 0) {
result |= num;
}
}
return result;
}
}
Explanation: Same as main approach but with more descriptive variable name.
Time Complexity: O(n) - single pass Space Complexity: O(1) - constant space
class Solution {
public int evenNumberBitwiseORs(int[] nums) {
return Arrays.stream(nums)
.filter(num -> num % 2 == 0)
.reduce(0, (a, b) -> a | b);
}
}
Explanation: Use Java streams to filter even numbers and reduce with OR operation.
Time Complexity: O(n) - stream processing Space Complexity: O(1) - excluding temporary stream objects
class Solution {
public int evenNumberBitwiseORs(int[] nums) {
int result = 0;
for (int num : nums) {
if ((num & 1) == 0) { // Check if even using bitwise AND
result |= num;
}
}
return result;
}
}
Explanation: Use bitwise AND with 1 to check if number is even (even numbers have LSB 0).
Time Complexity: O(n) - single pass Space Complexity: O(1) - constant space
class Solution {
public int evenNumberBitwiseORs(int[] nums) {
int result = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] % 2 == 0) {
result = result | nums[i];
}
}
return result;
}
}
Explanation: Use traditional for loop with index instead of enhanced for loop.
Time Complexity: O(n) - single pass Space Complexity: O(1) - constant space
| Property | Description | Example |
|---|---|---|
| Identity | x | 0 = x |
5 | 0 = 5 |
| Self | x | x = x |
5 | 5 = 5 |
| Commutative | x | y = y | x |
3 | 5 = 5 | 3 |
| Associative | (x | y) | z = x | (y | z) |
(1 | 2) | 4 = 1 | (2 | 4) |
Key Insights:
Binary Examples:
001001000110| 2 | 4 | 6 = 0110 (decimal 6) |
Edge Cases: