Program to find longest consecutive run of 1s in binary form of n in Python

PythonServer Side ProgrammingProgramming

Suppose we have a non-negative value n, we have to find the length of the longest consecutive run of 1s in its binary representation.

So, if the input is like n = 1469, then the output will be 4, because binary representation of 156 is "10110111101", so there are four consecutive 1s

To solve this, we will follow these steps −

  • count := 0
  • while n is not same as 0, do
    • n := n AND (n after shifting one bit to the left)
    • count := count + 1
  • return count

Example

Let us see the following implementation to get better understanding −

def solve(n):
   count = 0
   while n != 0:
      n = n & (n << 1)
      count = count + 1

   return count

n = 1469
print(solve(n))

Input

1469

Output

4
raja
Published on 19-Oct-2021 10:28:26
Advertisements