[LeetCode] Challenge log 693

693. Binary Number with Alterntive Bits

s1. n<<1 + n should be all 1s.

s2. similar to s1 but more pythonic

s3. check by bit


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
Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101

Example 2:

1
2
3
4
Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111.

Example 3:

1
2
3
4
Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.

Example 4:

1
2
3
4
Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010.

Soulution:
1
2
3
4
5
6
7
8
9
10
11
class Solution:
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
res = True
mask = 0
while mask < n:
mask = (mask << 1) + 1
return (n >> 1) + n == mask
1
2
3
4
5
6
7
class Solution:
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
return bin((n >> 1) + n).count('0') == 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
res = []
while n > 0:
res.append(n % 2)
n = n // 2
if len(res) <= 1: return True
for i in range(1, len(res)):
if res[i] == res[i-1]:
return False
return True
0%