Search code examples
python-3.xrecursion

converting int to string using recursion


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

  • I'd do:

    def int_to_string(n):
        i, j = n // 10, n % 10
        return (int_to_string(i) if i > 0 else "") + chr(j + 48)
    
    
    s = int_to_string(125)
    print(s, type(s))
    

    Prints:

    125 <class 'str'>