Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading