使用 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' 方法用于将给定的数字转换为特定的基数。

  • 根据输出是否为特定碱基,返回 Yes 或 No。

  • 'check_n' 方法用于检查数字是否为 0。

  • N 和 K 的值已定义。

  • 'check_consecutive_zero' 方法通过传递 N 和 K 来调用。

  • 输出显示在控制台上。

以上是 使用 Python 检查一个数字是否在给定的基数中有连续的 0 的全部内容, 来源链接: utcz.com/z/341440.html

回到顶部