converting int to string using recursion

Advertisements

I know in python we can easily convert an int to string with str(). I would like to convert int to string using recursion and not using str(). I came up with the following which appears to work but looks overly complicated. Is there a cleaner, elegant, more efficient algorithm?

def intTOstring(n,text=""):
    if n == 0:
        return text
    elif n < 10 and n > 0:
        return text + chr(n+48)
    else:
        x = n
        i = 0
        while(x >= 10):
            x = x // 10
            i += 1            
        n = n - x*10**i        
        text = text + chr(x+48)
        if n < 10**(i-1):
            text = text + chr(48)
        return intTOstring(n,text)
    
print(intTOstring(125))

>Solution :

Yes, you can use the modulus to simplify your function

def intToString(n):
    if not n:
        return ""
    return intToString(n // 10) + chr(48 + n % 10)

Leave a ReplyCancel reply