| # Binary Number with Alternating Bits (LeetCode 693)
|
|
|
| Check whether adjacent bits always differ.
|
|
|
| ```python
|
| def hasAlternatingBits(n):
|
| x = n ^ (n >> 1)
|
| return (x & (x + 1)) == 0
|
| ```
|
|
|
| XOR with the right-shift; then one contiguous block of 1-bits means alternating.
|
|
|
| Practice with [Linkjob AI](https://www.linkjob.ai/interview-copilot/).
|
|
|
| (Affiliation: I work on Linkjob AI.)
|