LeetCode 693 Binary Number with Alternating Bits 解题报告
作者:互联网
题目要求
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
题目分析及思路
给定一个正整数,判断它的二进制形式是否是01交替出现。如果是则返回True,否则返回False。可以先获得该数的二进制形式,之后利用切片分别获得其奇数位和偶数位的值。若全为1或0,则是满足要求的数。
python代码
class Solution:
def hasAlternatingBits(self, n: int) -> bool:
b_str = bin(n)
b_substr = b_str[2:]
evens = b_substr[0::2]
odds = b_substr[1::2]
if evens.count('1') == len(evens) and odds.count('0') == len(odds):
return True
else:
return False
标签:Alternating,693,return,Binary,True,odds,substr,evens,bits 来源: https://www.cnblogs.com/yao1996/p/10499514.html