[Bit Operation-Simple] 693. Alternating Bit Binary Number

[Title]
Given a positive integer, check whether its binary representation is always 0 and 1 alternately: in other words, the two adjacent digits in the binary representation are never the same.
[Example 1]
Input: n = 5
Output: true
Explanation: The binary representation of 5 is: 101
[Example 2]
Input: n = 7
Output: false
Explanation: The binary representation of 7 is: 111.
[Example 3]
Input: n = 11
Output: false
Explanation: The binary representation of 11 is: 1011.
[Example 4]
Input: n = 10
Output: true
Explanation: The binary representation of 10 is: 1010.
[Example 5]
Input: n = 3
Output: false
【 Prompt]
1 <= n <= 231-1
[Code]
[Python]
Insert picture description here

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

[Method 2: Bit operation]
Insert picture description here

class Solution:
    def hasAlternatingBits(self, n: int) -> bool:      
        x=(n^(n>>1))
        return x&(x+1)==0

Guess you like

Origin blog.csdn.net/kz_java/article/details/115118345