
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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