Post

693 Binary Number With Alternating Bits

693 Binary Number With Alternating Bits

Binary Number with Alternating Bits image

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

 

Example 1:

1
2
3
4
5
**Input:** n = 5
**Output:** true
**Explanation:** The binary representation of 5 is: 101

Example 2:

1
2
3
4
**Input:** n = 7
**Output:** false
**Explanation:** The binary representation of 7 is: 111.

Example 3:

1
2
3
4
**Input:** n = 11
**Output:** false
**Explanation:** The binary representation of 11 is: 1011.

 

Constraints:

1
1 <= n <= 231 - 1
1
2
3
4
5
6
7
8
9
10

class Solution(object):
    def hasAlternatingBits(self, n):
        bits = bin(n)
        return all(bits[i] != bits[i+1]
                   for i in range(len(bits) - 1))



This post is licensed under CC BY 4.0 by the author.