Problem
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.Examples
Constraints
- 1 <= n <= 2^31 - 1
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 693 with 18 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 693 # by problem number
lcpy gen -s binary_number_with_alternating_bits # by problem name
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.
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
| Time | Space |
|---|---|
| O(1) (at most 31 iterations for the 32-bit constraint) | O(1) |