输入一个十进制整数
。
输出一个整数,表示
的二进制表示中,最长连续
段的长度。
200
2
在这个样例中,十进制
等于二进制
,其中最长连续
段的长度为
。
1023
10
在这个样例中,十进制
等于二进制
。
本题数据已规范为单组询问(2025/01/15)。
转换为二进制字符串后用'0'切片
b = bin(int(input()))[2:]
ll = b.split('0')
tt = sorted(list(set(ll)), key=lambda x:len(x), reverse=True)
print(len(tt[0])) 转换为二进制字符串后遍历
n = int(input())
binary = bin(n)[2:] # 去掉 '0b' 前缀
maxLen = currentLen = 0
for bit in binary:
if bit == '1':
currentLen += 1
maxLen = max(maxLen, currentLen)
else:
currentLen = 0
print(maxLen) 利用位运算
n = int(input())
currCnt, maxCnt = 0, 0
while n:
if n & 1:
currCnt += 1
maxCnt = max(currCnt, maxCnt)
else:
currCnt = 0
n >>= 1
print(maxCnt)
import re n = bin(int(input()))[2:] print(max(len(s) for s in re.split(r'0+', n)))
while True:
try:
print(len(sorted(str(bin(int(input())))[2:].split('0'),reverse=True)[0]))
except:
break input_str = input() input_2_str = bin(int(input_str)) input_2_str = input_2_str[2:] longgest = 0 temp = 0 for i in input_2_str: if(i == "1"): temp = temp +1 else: if(temp != 0): if(temp > longgest): longgest = temp temp = 0 else: continue #这里注意一个边界条件,就是如果最后一直都是1,那么最后不会触发else的情况,导致无法更新longgest #所以循环结束后,还需要再判断一次是否保存 if(temp > longgest): longgest = temp print(longgest)
#法一:
n = bin(int(input()))[2:].split('0')
print(len(sorted(n)[-1]))
'''
法二:
temp = 0
lenth = 0
for i in n:
if i == '1':
temp += 1
else:
temp = 0
lenth = max(lenth,temp)
print(lenth)
''' n=int(input())
n=bin(n)
l=(n[2:].split('0'))
count=[]
for i in l:
count.append(len(i))
print(max(count))
a=int(input()) a=bin(a) a=str(a) b=[] for i in range (0,len(a)): cc=0 for j in range(i+1, len(a)): if a[i]=='1': if a[j]=='1': cc=cc+1 else: break b.append(cc+1) if max(b)==0: print(1) else: print(max(b))