Python 二进制数中连续1的计数
这是HackerRank第10天的代码问题(30天的代码挑战) 我已经算出了大部分部分,但我被困在了一个部分,你必须在二进制表示中计算连续1的数量 <>这个代码在整个系列的开始或中间的连续1s都很好用, 但在最后的连续1秒中,我不知道该怎么做Python 二进制数中连续1的计数,python,python-3.x,Python,Python 3.x,这是HackerRank第10天的代码问题(30天的代码挑战) 我已经算出了大部分部分,但我被困在了一个部分,你必须在二进制表示中计算连续1的数量 这个代码在整个系列的开始或中间的连续1s都很好用, 但在最后的连续1秒中,我不知道该怎么做 cons = 0 def bin_no(): global rem, cons #Input n = int(input("Enter Number : ")) rem=[] #
cons = 0
def bin_no():
global rem, cons
#Input
n = int(input("Enter Number : "))
rem=[]
#Checking If The Number Is Valid Or Not.
if n < 0:
print("Please Enter A Valid Number : ")
bin_no()
elif n == 0:
print('0000')
#While Loop for Conversion
while n >=1 :
rem.append(n%2)
n = n//2
rem.reverse()
print("Binary Representation ",*rem, sep = '')
#Finding Maximum Consecutive 1s.
maxcon = 0
for x in rem:
if x == 1:
cons += 1
elif x != 1 and cons > maxcon:
maxcon = cons
cons = 0
print(maxcon)
bin_no()
cons=0
def bin_no():
全球rem,cons
#输入
n=int(输入(“输入编号:”)
rem=[]
#检查号码是否有效。
如果n<0:
打印(“请输入有效数字:”)
本()
elif n==0:
打印('0000')
#用于转换的While循环
当n>=1时:
rem.append(n%2)
n=n//2
反向物
打印(“二进制表示”,*rem,sep=“”)
#查找最大连续1s。
maxcon=0
对于rem中的x:
如果x==1:
cons+=1
以利夫x!=1和cons>maxcon:
maxcon=cons
cons=0
打印(maxcon)
本()
您可以在代码末尾附近看到最大连续1s代码块
我知道该错误是由于列表结尾不包含任何
不等于1
因此,结束
elif
代码块将被忽略。您需要设置一个条件,在循环本身之后检查最大值,如您所述,最大连续1s即将结束:
#Finding Maximum Consecutive 1s.
maxcon, cons = 0, 0
for x in rem:
if x == 1:
cons += 1
elif x != 1 and cons > maxcon:
maxcon = cons
cons = 0
maxcon = max(maxcon, cons)
^^这应该可以解决它
编辑
顺便说一句,我提出了一个更优雅的解决方案,它不需要将数字转换为二进制格式:
N = int(14)
cons, maxcon = 0, 0
while N > 0:
if N & 1:
cons += 1
else:
maxcon = max(cons, maxcon)
cons = 0
N >>= 1
maxcon = max(cons, maxcon)
print(maxcon)
Serial Lazer的编辑绝对是正确的选择,但我只是想纠正他们的第一个答案
def consec_ones_a(rem):
count, largest = 0, 0
for x in rem:
if x == 1:
count += 1
else:
if count > largest:
largest = count
count = 0
return max(largest, count)
def consec_ones_b(rem):
maxcon, cons = 0, 0
for x in rem:
if x == 1:
cons += 1
elif x != 1 and cons > maxcon:
maxcon = cons
cons = 0
return max(maxcon, cons)
# 4 consecutive 1s
binary = [1,1,1,0,1,0,1,1,1,1]
print(consec_ones_a(binary))
print(consec_ones_b(binary))
输出
4
5
请添加一些带有输入和预期输出的测试用例,以便更加清晰
4
5