09 Sept 2026Go / Python / TypeScriptEasy

Binary Number with Alternating Bits

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.

complexity

O(log n) time and O(1) extra space.

solution files

  • Go binary-number-with-alternating-bits/solution.go
  • Python binary-number-with-alternating-bits/solution.py
  • TypeScript binary-number-with-alternating-bits/solution.ts

Solution files

Gobinary-number-with-alternating-bits/solution.go
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
}
Pythonbinary-number-with-alternating-bits/solution.py
class Solution:
    def hasAlternatingBits(self, n: int) -> bool:
        previous = n & class="syntax-number">1
        n >>= class="syntax-number">1
        while n:
            current = n & class="syntax-number">1
            if current == previous: return False
            previous, n = current, n >> class="syntax-number">1
        return True
TypeScriptbinary-number-with-alternating-bits/solution.ts
function hasAlternatingBits(n: number): boolean {
  let previous = n & class="syntax-number">1;
  n >>= class="syntax-number">1;
  while (n > class="syntax-number">0) { const current = n & class="syntax-number">1; if (current === previous) return false; previous = current; n >>= class="syntax-number">1; }
  return true;
}