描述
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Input: n = 5
Output: true
Explanation: The binary representation of 5 is: 101
Example 2:
Input: n = 7
Output: false
Explanation: The binary representation of 7 is: 111.
Example 3:
Input: n = 11
Output: false
Explanation: The binary representation of 11 is: 1011.
Example 4:
Input: n = 10
Output: true
Explanation: The binary representation of 10 is: 1010.
Example 5:
Input: n = 3
Output: false
Note:
1 <= n <= 2^31 - 1
解析
根据题意,就是将 n 转换为二进制,然后判断这个二进制的相邻位上的数字是否总是不同的。
解答
class Solution(object):
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
r = ''
while n>0:
m = str(n%2)
if r and r[-1]==m:
return False
r += m
n//=2
return True
运行结果
Runtime: 32 ms, faster than 6.54% of Python online submissions for Binary Number with Alternating Bits.
Memory Usage: 13.5 MB, less than 35.51% of Python online submissions for Binary Number with Alternating Bits.
原题链接:leetcode.com/problems/bi…
您的支持是我最大的动力