[英]Counting Consecutive 1s in a Binary Number
This is a HackerRank Day 10 Code Problem (30 Days of Code Challenge)这是 HackerRank 第 10 天代码问题(30 天代码挑战)
I have figured out most of the part but I am stuck at the part where you have to count the number of consecutive 1s in a binary representation.我已经弄清楚了大部分内容,但我仍然停留在您必须计算二进制表示中连续 1 的数量的部分。
The code works just fine for consecutive 1s in the beginning or in the middle of the whole series, But for consecutive 1s at the end I can't figure out what to do该代码对于整个系列的开头或中间的连续 1 都可以正常工作,但是对于最后的连续 1,我不知道该怎么做
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()
You can see the Maximum Consecutive 1s code block near the end of the code.您可以在代码末尾附近看到 Maximum Consecutive 1s 代码块。
I know the error is caused due to the ending of the list doesn't contain any element that is我知道错误是由于列表的结尾不包含任何元素引起的
not equal to 1
不等于 1
Thus the ending elif
code block is ignored.因此,结尾的
elif
代码块将被忽略。
You need to setup a condition to check the maximality after the loop itself incase as you mentioned the maximum-consecutive-1s are towards the end:您需要设置一个条件来检查循环本身之后的最大值,因为您提到 max-consecutive-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)
^^This should fix it ^^这应该解决它
Btw, I come up with a more elegant solution which doesnt require converting the number into its binary format:顺便说一句,我想出了一个更优雅的解决方案,不需要将数字转换为二进制格式:
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)
3
Serial Lazer's edit is definitely the way to go, but I just wanted to correct their first answer. 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))
outputs产出
4
5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.