Search code examples
pythonreversebase-conversion

How to reverse integer values from a while loop?


I am trying to write a program to convert a base 10 (decimal) number into a base 4 number. Here is the code I have come up with:

def decimal_to_base4(num):
    while num > 0:
        quotient = num//4
        base4 = num%4
        num = quotient
        print(base4, end="")
decimal_to_base4()

This code works fine, except for one problem:

For example, if my parameter value is 45, the output becomes 132. However since the base-4 value of 45 is 231, I want that output to be reversed to 231. How can I do that? I am having difficulties joining the integer outputs from the while loop, and reversing the same.


Solution

  • You could build the integer one digit at a time, then print it:

    def decimal_to_base4(num):
        result=""
        while num > 0:
            quotient = num//4
            result+=str(num%4)
            num = quotient
        result = result[::-1]
        print(result, end="")