Leetcode 2980. Check if Bitwise OR Has Trailing Zeros
Given a non-negative integer n, you need to determine whether the bitwise OR of this number and any one-bit number (i.e., a number that has exactly one 1-bit) has trailing zeros. Trailing zeros are zeros in the least significant positions of a binary number.
Example:
n
fall within?
n
will be a non-negative integer within the range of 32-bit or 64-bit integers.n
can be observed by looking at the binary form from the least significant bit onwards.n
can be determined using n & (-n)
, which gives us the least significant 1-bit as a power of two. The number of trailing zeros corresponds to the position of this bit.n
has trailing zeros, then the bitwise OR with any number that has the 1-bit higher than or equal to the position of the least significant 1-bit of n will keep the trailing zeros intact.n
.1
in positions greater than or equal to the position of the least significant 1-bit of n
to see if trailing zeros are maintained.Here’s the implementation of the solution in C++:
#include <iostream>
bool hasTrailingZeros(int n) {
if (n == 0) {
return true; // OR with any 1-bit number will be non-zero, hence will have trailing zeros.
}
// Calculate the number of trailing zeros in n
int trailingZerosCount = __builtin_ctz(n);
// Generate a number with exactly one 1-bit in the position `trailingZerosCount`
int positionBit = 1 << trailingZerosCount;
// Check if OR operation with this number maintains trailing zeros
int result = n | positionBit;
return (__builtin_ctz(result) > trailingZerosCount);
}
int main() {
int n = 8; // Example input
bool result = hasTrailingZeros(n);
std::cout << (result ? "True" : "False") << std::endl;
return 0;
}
The time complexity of this solution is O(1) because:
__builtin_ctz
is a constant time operation, which is hardware-assisted.Thus, this approach has efficient time complexity suitable for a competitive programming environment.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?