Computer >> Máy Tính >  >> Lập trình >> Python

Chương trình Python để tìm độ dài của 1 liên tiếp lớn nhất trong Biểu diễn nhị phân của một chuỗi đã cho.

Cho trước số, hãy tìm độ dài của 1 liên tiếp dài nhất trong biểu diễn nhị phân của nó.

Ví dụ

Input: n = 15
Output: 4
The binary representation of 14 is 1111.

Thuật toán

Step 1: input the number.
Step 2: use one counter variable c=0.
Step 3: Count the number of iterations to reach i = 0.
Step 4: This operation reduces length of every sequence of 1s by one.

Mã mẫu

# Python program to find
# length of the longest
# consecutive 1s in
# binary representation of a number.
def maxlength(n):
   # Initialize result
   c = 0
   # Count the number of iterations to
   # reach x = 0.
   while (n!=0):
      # This operation reduces length
      # of every sequence of 1s by one.
      n = (n & (n << 1))
      c=c+1
   return c
# Driver code
n=int(input("Enter The Number ::>"))
print("Maximum Length of 1's ::>",maxlength(n))

Đầu ra

Enter The Number ::>15
Maximum Length of 1's ::>4