- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions

# 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

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

- Related Articles
- Program to find longest consecutive run of 1s in binary form of n in Python
- 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 longest subarray of 1s after deleting one element using Python
- Program to find length of longest substring with 1s in a binary string after one 0-flip in Python
- Program to find number of boxes that form longest chain in 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
- Program to find longest even value path of a binary tree in Python
- Sorting according to number of 1s in binary representation using JavaScript
- Program to find number of special positions in a binary matrix using Python
- Find row number of a binary matrix having maximum number of 1s in C++