[LeetCode]Binary Number with Alternating Bits

题目描述:

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.

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.

题目大意:

给定正整数,判断其二进制是否01交替。

解题思路:

解法I 进制转换

Python代码:

class Solution(object):
    def hasAlternatingBits(self, n):
        """
        :type n: int
        :rtype: bool
        """
        n = bin(n)
        return all (n[x] != n[x + 1] for x in range(len(n) - 1))

解法II 位运算

Python代码:

class Solution(object):
    def hasAlternatingBits(self, n):
        """
        :type n: int
        :rtype: bool
        """
        last = n & 1
        n >>= 1
        while n:
            bit = n & 1
            if bit == last: return False
            last = bit
            n >>= 1
        return True

 

本文链接:http://bookshadow.com/weblog/2017/10/08/leetcode-binary-number-with-alternating-bits/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码