Compare each least-significant bit with the previous bit while shifting the number to the right.
Complexity
O(log n) time and O(1) extra space.
Determine whether adjacent bits in a positive integer alternate between zero and one.
Compare each least-significant bit with the previous bit while shifting the number to the right.
O(log n) time and O(1) extra space.
package main
func hasAlternatingBits(n int) bool {
previous := n & 1
n >>= 1
for n > 0 {
current := n & 1
if current == previous {
return false
}
previous = current
n >>= 1
}
return true
}
class Solution:
def hasAlternatingBits(self, n: int) -> bool:
previous = n & 1
n >>= 1
while n:
current = n & 1
if current == previous: return False
previous, n = current, n >> 1
return True
function hasAlternatingBits(n: number): boolean {
let previous = n & 1;
n >>= 1;
while (n > 0) { const current = n & 1; if (current === previous) return false; previous = current; n >>= 1; }
return true;
}