> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Binary Number with Alternating Bits

> Tested Python solution for LeetCode 693 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 693, [Easy](/catalog/easy). Topics: [Bit Manipulation](/catalog/topics/bit-manipulation). [View on LeetCode](https://leetcode.com/problems/binary-number-with-alternating-bits/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 693   # by problem number
lcpy gen -s binary_number_with_alternating_bits   # by problem name
```

## Problem

Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.

### Examples

```
Input: n = 5
Output: true
Explanation: The binary representation of 5 is: 101
```

```
Input: n = 7
Output: false
Explanation: The binary representation of 7 is: 111.
```

```
Input: n = 11
Output: false
Explanation: The binary representation of 11 is: 1011.
```

### Constraints

* 1 \<= n \<= 2^31 - 1

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/binary_number_with_alternating_bits/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/binary_number_with_alternating_bits/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(1) (at most 31 iterations for the 32-bit constraint)
    # Space: O(1)
    def has_alternating_bits(self, n: int) -> bool:
        # x = n ^ (n >> 1) has every bit set iff adjacent bits all differ;
        # adding the carry back onto x must produce the next power of two.
        x = n ^ (n >> 1)
        return x & (x + 1) == 0
```

## Complexity

| Time | Space |
| - | - |
| O(1) (at most 31 iterations for the 32-bit constraint) | O(1) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.