Given a positive integer n, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
n can be?
n can be any positive integer within the typical 32-bit signed integer range.True if the integer has alternating bits, otherwise False.n to its binary representation.False.True.n to a binary string using Python’s built-in bin() function and strip off the '0b' prefix.False.True.def hasAlternatingBits(n: int) -> bool:
# Get the binary representation of the number, without the '0b' prefix
binary_str = bin(n)[2:]
# Loop through the binary string
for i in range(len(binary_str) - 1):
# Check if the current bit is the same as the next bit
if binary_str[i] == binary_str[i + 1]:
return False
return True
# Example usage:
print(hasAlternatingBits(5)) # True, binary: '101'
print(hasAlternatingBits(7)) # False, binary: '111'
print(hasAlternatingBits(11)) # False, binary: '1011'
print(hasAlternatingBits(10)) # True, binary: '1010'
bin(n) function has a time complexity of (O(\log n)) where (n) is the input integer.The overall time complexity is dominated by these operations and can be considered (O(\log n)).
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?