简体   繁体   中英

Iterative to Recursive format

I'm finding it difficult to write the below-mentioned code (Int to Binary) in recursive format. Please help me clear my doubt that what am I missing to achieve this conversion.

Here's the code:

class Stack:
   
   def __init__(self):
     self.number = []

   def push(self, number):
     self.number.append(number)

   def pop(self):
     return self.number.pop()

   def is_empty(self):
     return self.number == [] 

   def int_to_binary(number):
     s = Stack()
     while number > 0:
        remainder = number % 2
        s.push(remainder)
        number = number // 2

     set =''
     while not s.is_empty():
        set += str(s.pop())
        print(set)
   print(int_to_binary(243))

It usually isn't at all helpful to look at an iterative solution to a problem to translate it to a recursive solution. Insetad, you need to think recursively from the begginning. Just like every programming problem, you should start by describing the solution in words. But now we need to describe it in a recursive way instead of an iterative way.

We first describe all the base cases:

The binary representation of n = 0 is '0'

The binary representation of n = 1 is '1'

Then we describe the recursive case:

The binary represenation of a number n is the binary representation of n divided by 2 (without the remainder) followed by n mod 2.

Notice how the description is self-referential. This is what makes it recursive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM