describe

Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.

Example 1:

Input: n = 5
Output: true
Explanation: The binary representation of 5 is: 101
Copy the code

Example 2:

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

Example 3:

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

Example 4:

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

Example 5:

Input: n = 3
Output: false
Copy the code

Note:

1 <= n <= 2^31 – 1

parsing

Convert n to binary and determine whether the numbers in the adjacent bits of the binary are always different.

answer

class Solution(object):
    def hasAlternatingBits(self, n):
        """
        :type n: int
        :rtype: bool
        """
        r = ''
        while n>0:
            m = str(n%2)
            if r and r[-1]==m:
                return False
            r += m
            n//=2
        return True
        	      
		
Copy the code

The results

Given in the Python online submissions with Alternating Bits. Memory Usage: 10000 ms Given in Python online submissions for Binary Number with Alternating Bits.Copy the code

Original link: leetcode.com/problems/bi…

Your support is my biggest motivation