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:

扫描二维码关注公众号,回复: 5471943 查看本文章

            return False

        

猜你喜欢

转载自www.cnblogs.com/yao1996/p/10499514.html