Leetcode 693 Solution

This article provides solution to leetcode question 693 (binary-number-with-alternating-bits)

https://leetcode.com/problems/binary-number-with-alternating-bits

Solution

class Solution: def hasAlternatingBits(self, n: int) -> bool: last_b = 0
while n: a = n & (n - 1) b = n ^ a
if (last_b != 0 and 4 * last_b != b) or (last_b == 0 and b > 2): return False
last_b = b n = a
return True