Check if Bitwise OR Has Trailing Zeros Solution in C++

Problem Description

So, you want to check if the Bitwise OR of a bunch of numbers has trailing zeros? Imagine you’re at a party, and you’re trying to figure out if the last slice of pizza is still there. You know, the one that everyone pretends they don’t want, but deep down, we all know it’s the best one. Similarly, in the world of numbers, trailing zeros are like that last slice—sometimes they’re there, and sometimes they’re not.

In this problem, you’re given an array of integers, and your task is to determine if there are at least two even numbers in the array. Why? Because two even numbers guarantee that the Bitwise OR will have trailing zeros. It’s like saying, “If I have two even friends, we can definitely share that last slice of pizza!”

Code Solution


class Solution {
 public:
  bool hasTrailingZeros(vector& nums) {
    int countEven = 0;

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

    return countEven >= 2;
  }
};

Approach

The approach here is straightforward. The code iterates through the array of integers and counts how many of them are even. If there are at least two even numbers, it returns true, indicating that the Bitwise OR will have trailing zeros. It’s like counting how many friends you have who are willing to share that pizza slice—if you have two, you’re golden!

Time and Space Complexity

Time Complexity: O(n), where n is the number of elements in the input 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 at a family gathering, and you’re trying to figure out how many of your relatives are willing to chip in for a group gift. If you find at least two of them who are ready to contribute, you can go ahead and buy that fancy gift. Similarly, in our problem, if we find at least two even numbers, we can confidently say that the Bitwise OR will have trailing zeros.

Similar Problems

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