leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

binary_num_alter_bits.py (522B)


# 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
"""


class Solution(object):
    def hasAlternatingBits(self, n):
        """
        :type n: int
        :rtype: bool
        """
        n ^= n >> 1
        return (n & n + 1) == 0


if __name__ == "__main__":
    obj = Solution()
    print(obj.hasAlternatingBits(5))
    print(obj.hasAlternatingBits(7))
    print(obj.hasAlternatingBits(11))