Check if Bitwise OR Has Trailing Zeros Solution in Java

Problem Description

So, you think you can just throw a bunch of integers into a bitwise OR operation and not worry about the consequences? Well, think again! The problem at hand is to check if the result of the bitwise OR operation on an array of integers has trailing zeros. Yes, trailing zeros! Just like that last slice of pizza that no one wants to take, but it’s still there, lingering at the bottom of the box.

Imagine you’re at a party, and you’ve got a bunch of friends (the integers) who are all trying to show off their dance moves (the bitwise OR). But if they can’t manage to get at least two of them to dance in sync (i.e., be even), then the party is a total flop!

Code Solution


class Solution {
  public boolean hasTrailingZeros(int[] nums) {
    int countEven = 0;

    for (final int num : nums)
      if (num % 2 == 0)
        ++countEven;

    return countEven >= 2;
  }
}

Approach

The approach here is as straightforward as it gets. We simply loop through the array of integers and count how many of them are even. If we find at least two even numbers, we can confidently say that the bitwise OR will have trailing zeros. It’s like counting how many friends are willing to share that last slice of pizza—if two or more are willing, you know it’s going to be a good time!

Time and Space Complexity

Time Complexity: O(n), where n is the number of elements in the array. We traverse the array once to count the even numbers.

Space Complexity: O(1), as we are using a constant amount of space for the count variable.

Real-World Example

Let’s say you’re organizing a game night with your friends. You want to ensure that at least two of your friends can play the game that requires even-numbered players. If you have a group of friends (the integers) and you find that at least two of them can play (are even), then you’re all set for a fun night! If not, well, it’s just you and the pizza again.

Similar Problems

If you enjoyed this problem, you might also want to check out these similar challenges: