Program to find longest distance of 1s in binary form of a number using Python


Suppose we have a number N, we have to find the longest distance between two consecutive 1's in its binary representation. If there are no two-consecutive 1's, then return 0.

So, if the input is like 71, then the output will be 4, because 71 in binary is 1000111. Now there are four ones, and first 1 and the second 1 are at distance 4. All others are one distance away. So longest distance is 4 here.

To solve this, we will follow these steps −

  • K := make a list of bits of binary representation of N

  • Max := 0, C := 0, S := 0

  • Flag := False

  • for i in range 0 to size of K, do

    • if K[i] is '1' and C is 0 and Flag is False, then

      • C:= i

      • Flag := True

    • otherwise when K[i] is '1' and Flag, then

      • S:= i

      • if Max<abs(S-C), then

        • Max := |S-C|

      • C:= S

  • return Max

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(N):
   B = bin(N).replace('0b','')
   K = str(B)
   K = list(K)
   Max = 0
   C = 0
   S = 0
   Flag = False
   for i in range(len(K)):
      if K[i] is '1' and C is 0 and Flag is False:
         C = i
         Flag = True
      elif K[i] is '1' and Flag:
         S = i
         if Max<abs(S-C):
            Max = abs(S-C)
         C = S
   return Max
n = 71
print(solve(n))

Input

71

Output

4

Updated on: 29-May-2021

155 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements