【LeetCode】693. Binary Number with Alternating Bits

Python版本:python3.6.2

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.
Example 1:
Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101
Example 2:
Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111.
Example 3:
Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.
Example 4:
Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010.


感觉自己的解法很蠢,坐等大神的代码:
class Solution:
    def hasAlternatingBits(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if len(list(bin(n))) > 3:
            tmp = list(bin(n))[2]
            flag = 0
            for i in range(3, len(list(bin(n)))):
                if tmp == '1':     #翻转,例如:tmp为1,则re_tmp为0;
                    re_tmp = '0'
                else:
                    re_tmp = '1'
                if list(bin(n))[i] == re_tmp:
                    flag += 1
                    tmp = re_tmp
            if flag == len(list(bin(n))) - 3:
                return True
            else:
                return False
        else:
            return True
检验下:
a = Solution()
print(a.hasAlternatingBits(1))
输出:
True
速度:
【LeetCode】693. Binary Number with Alternating Bits_第1张图片

立马来看看大神的Solution:
class Solution:
    def hasAlternatingBits(self, n):
        return '00' not in bin(n) and '11' not in bin(n)
我跟大神的差距在于一个灵活的脑子,我的脑子太死了,按照作者的意思解题,不活。
解题还是要灵活点,多动动脑子。

你可能感兴趣的:(LeetCode)