Question:
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Solution:
Question Setting requires determining a number in the form of 101010. How can we give an algorithm with the minimum complexity?
First, let's take a look at the basic tools to solve this question using python.
Speaking of binary, the first thing that comes to mind is the bitwise operator number. The Python bitwise operator numbers include ~ |>><<.
First look at the shift, it is easy to find that if you move 101010 to the right, there will be 10101, the sum of the two is 111111; When 111111 to 1, it will get 0 with its own and the operation
Try to write the problem-solving Code as follows:
ClassSolution: defHasalternatingbits (self, n): Return (n + (n> 1) & (n + (n> 1) + 1) = 0
Submission result: accepted
Leetcode-693. Binary Number with alternating bits