Home > Back-end >  I cannot understand this DecimalToBinary recursive function
I cannot understand this DecimalToBinary recursive function

Time:06-27

I found this code but I can't understand this:

def DecimalToBinary(num):
    if num >= 1:
        DecimalToBinary(num // 2)
    print(num % 2, end = '')

if __name__ == '__main__':
    dec_val = 24
    DecimalToBinary(dec_val)

CodePudding user response:

It's easier if you can run this code in such a visual platform first - https://pythontutor.com/ and see each step execution.

But this recursive function just did these two/three things:

if num >= 1:                      # if num is greater or equal to 1: do next
    DecimalToBinary(num // 2) # recusive call -> put this new num // 2
                                  # 6 -> 3 -> 1 -> 0  eg. starting with 6 and go to next loop/recursive call.  Temp. result is stored in `stack` for later

print(num % 2, end = '')      # now it's out of the loop (all done - reaching 0), so we check if this num's remainder  by module (%) - and get 0 or 1 and start to return it as 0 or 1. As such we got -> 0110 as the final output.

output

0110

CodePudding user response:

This is a recursive code. You pass the number to the function till it is not grater than 1, and since you have to print the binary of decimal which is in reverse order you have added print statement after the function call. The call for the function is a call by value and does not update the number.

  • Related