使用Python检查给定进制的数字是否包含连续的0
当需要检查一个数字在特定进制下是否包含连续的零时,我们定义一个方法,该方法将数字和进制作为参数,并使用另一个方法根据特定进制是否存在返回“是”或“否”。
下面是演示:
示例
def check_consecutive_zero(N, K):
my_result = convert_to_base(N, K)
if (check_n(my_result)):
print("Yes")
else:
print("No")
def convert_to_base(N, K):
weight = 1
s = 0
while (N != 0):
r = N % K
N = N//K
s = r * weight + s
weight*= 10
return s
def check_n(N):
res = False
while (N != 0):
r = N % 10
N = N//10
if (res == True and r == 0):
return False
if (r > 0):
res = False
continue
res = True
return True
N, K = 8, 2
print("Does the number have consecutive zeroes in the base ?")
check_consecutive_zero(N, K)输出
Does the number have consecutive zeroes in the base ? No
解释
定义了一个名为“check_consecutive_zero”的方法,该方法接受数字和进制作为参数。
使用“convert_to_base”方法将给定数字转换为特定进制。
根据输出是否为特定进制,返回“是”或“否”。
使用“check_n”方法检查数字是否为0。
定义N和K的值。
通过传递N和K来调用“check_consecutive_zero”方法。
在控制台上显示输出。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP