Python 程序检查二进制数中是否存在 K 个连续 1?


首先,我们输入一个由 1 和 0 组合成的用户字符串。然后,创建一个由 1 组成的新字符串,接下来检查是否存在任意数量的连续 1。如果存在,则显示 FOUND,否则显示 NOTFOUND。

示例

Binary number ::1111001111
Enter consecutive 1’s :3
Consecutive 1's is Found

算法

Step 1: input a string with the combination of 1’s, it’s stored in the variable X and 0’s and p is the consecutive 1’s in a binary number.
Step 2: form a new string of p 1’s.
   newstring=”1”*p
Step 3: check if there is p 1’s at any position.
   If newstring in X
      Display “FOUND”
   Else
      Display “NOT FOUND”
   End if

示例代码

# To check if there is k consecutive 1's in a binary number 
def binaryno_ones(n,p):
   # form a new string of k 1's 
   newstr = "1"*p

   # if there is k 1's at any position 
   if newstr in n:
      print ("Consecutive 1's is Found")
   else:
      print (" Consecutive 1's is Not Found")

# driver code
n =input("Enter Binary number ::")
p = int(input("Enter consecutive 1's ::"))
binaryno_ones(n, p)

输出

Enter Binary number ::1111001111
Enter consecutive 1's ::3
Consecutive 1's is Found

更新于:30-Jul-2019

297 次浏览

开启你的 职业生涯

完成课程获得认证

立即开始
广告