Issue
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 n < 10:
return chr(n % 10 + 48)
return intToString(n // 10) + chr(n % 10 + 48)
Answered By - Hoxha Alban
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.