Python程序在给定字符串的二进制表示中查找最大连续1的长度。
给定数字,找到其二进制表示形式中最长的连续1的长度。
示例
Input: n = 15 Output: 4 The binary representation of 14 is 1111.
算法
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.
范例程式码
# 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))输出结果
Enter The Number ::>15 Maximum Length of 1's ::>4
热门推荐
7 简短的二胎祝福语
10 简短霸气女儿生日 祝福语
11 祝福语高考小众诗句简短
12 元旦祝福语20秒简短
13 老师过年祝福语大全 简短
14 一生祝福语简短
15 产检祝福语简短霸气
16 朋友店开张祝福语简短
17 生日爱情祝福语大全简短
18 朋友女儿生日祝福语 简短