requirements

Given a positive integer, check whether its binary representation always alternates zeros and ones: in other words, the two adjacent digits in the binary representation are never the same.

Example 1:

Input: n = 5 Output: true Description: Binary representation of 5 is: 101Copy the code

Example 2:

Input: n = 7 Output: false Description: binary representation of 7 is: 111.Copy the code

Example 3:

Input: n = 11 Output: false Description: the binary representation of 11 is: 1011.Copy the code

Example 4:

Input: n = 10 Output: true Description: The binary representation of 10 is: 1010.Copy the code

Example 5:

Input: n = 3 Output: falseCopy the code

The core code

class Solution:
    def hasAlternatingBits(self, n: int) - >bool:
        n,flag = divmod(n,2)
        while n:
            n,t = divmod(n,2)
            if t == flag:
                return False
            flag = t
        return True
Copy the code

Another solution

class Solution:
    def hasAlternatingBits(self, n: int) - >bool:
        b = bin(n)[2:]
        b = list(b)
        for i in range(len(b)-1) :if b[i] == b[i+1] :return False
        return True
Copy the code

The first solution is to continually use divmod to get the quotient and remainder, and then compare the remainder of the preceding digit with the remainder of the following digit. If the remainder is the same, return False. The second solution is to use bin as a binary string, iterating over the relationship between the first and last bits.