Check whether a number has consecutive 0’s in the given base or not using Python

PythonServer Side ProgrammingProgramming

When it is required to check if a number has consecutive zeroes of a specific base, a method is defined, that takes the number and base as parameters, and uses another method to return Yes or No depending on whether the base is present or not.

Below is a demonstration of the same −

Example

 Live Demo

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)

Output

Does the number have consecutive zeroes in the base ?
No

Explanation

  • A method named ‘check_consecutive_zero’ is defined that takes the number and base.

  • The ‘convert_to_base’ method is used to convert the given number to a specific base.

  • Depending on whether the output is of a specific base, Yes or No is returned.

  • The ‘check_n’ method is used to check if the number is 0.

  • The value for N and K are defined.

  • The ‘check_consecutive_zero’ method is called by passing N and K.

  • The output is displayed on the console.

raja
Published on 15-Apr-2021 13:44:18
Advertisements