- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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))

71

4

- Related Questions & Answers
- Longest distance between 1s in binary JavaScript
- Program to find longest consecutive run of 1 in binary form of a number in C++
- Program to find longest number of 1s after swapping one pair of bits in Python
- Program to find number of boxes that form longest chain in Python?
- Program to find longest subarray of 1s after deleting one element using Python
- Program to find number of substrings with only 1s using Python
- Program to find length of longest set of 1s by flipping k bits in Python
- Program to find length of longest alternating path of a binary tree in python
- Program to find length of longest consecutive path of a binary tree in python
- Find row number of a binary matrix having maximum number of 1s in C++
- Program to find longest even value path of a binary tree in Python
- Program to find number of special positions in a binary matrix using Python
- Sorting according to number of 1s in binary representation using JavaScript
- Program to find land with longest distance from water in Python
- Find consecutive 1s of length >= n in binary representation of a number in C++

Advertisements