-2

I have come across the question in leetcode on checking whether the number has alternative bits or not ?. Clear explanation of the question is given below. And this question is solved in stack overflow too. Stackoverflow Solution.

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

I know how to solve the question using for loop by checking whether two bits are same or not (i.e previous bit and the present bit is same or not). But i was intrigued by the below solution in leetcode

(n & (n >> 1)) == 0 && (n & (n >> 2)) == (n >> 2)

I am concerned about the understanding behind this one line code. Examples please !!

General Grievance
  • 4,555
  • 31
  • 31
  • 45
James K J
  • 605
  • 1
  • 8
  • 20

1 Answers1

1

Lets start with n & (n >> 1) == 0: if the bits are alternating, then there would be 0 overlap, and so & would return 0.

The second part makes sure that the bits aren't all 0 and ensures the last bits which are discarded with the shift are still consistent