You have been given an integer x and a non-negative integer k. Your task is to check if the bitwise OR of the integer x with 2^k - 1 has at least k trailing zeros in its binary representation.
Write a function hasTrailingZeros(x: int, k: int) -> bool that returns True if the condition is met, otherwise False.
x = 8, k = 3TrueThe integer 8 in binary form is 1000. The integer 2^3 - 1 is 7 which is 111 in binary. Bitwise OR of 1000 and 111 is 1111, and it has 3 trailing zeros.
x and k?
x?
2^k - 1.x and 2^k - 1.k trailing zeros.True if it does, otherwise False.To check for trailing zeros, the condition res & (2^k - 1) == 0 can be used, where res is the result of the bitwise OR operation, as this will check if the last k bits are zero.
def hasTrailingZeros(x: int, k: int) -> bool:
mask = (1 << k) - 1 # This creates a number with `k` trailing ones
result = x | mask
# Check if the result has at least `k` trailing zeros
return (result & mask) == 0
# Example Usage
print(hasTrailingZeros(8, 3)) # Output: True, `1000 | 0111 = 1111`
print(hasTrailingZeros(0, 2)) # Output: True
print(hasTrailingZeros(15, 4)) # Output: False
print(hasTrailingZeros(32, 5)) # Output: True
print(hasTrailingZeros(7, 3)) # Output: False
This function should now be efficient and handle the problem as described.
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?