Skip to content

Instantly share code, notes, and snippets.

@o3o3o
Created December 26, 2018 07:37
Show Gist options
  • Select an option

  • Save o3o3o/42af0b3dea6cea38d1630c65ba07e214 to your computer and use it in GitHub Desktop.

Select an option

Save o3o3o/42af0b3dea6cea38d1630c65ba07e214 to your computer and use it in GitHub Desktop.
reverse integers with tail recurse
# Execice for tail recurse
# Reverse the integr, strip 0
# if 0 is the first num
#
# e.g: 123450 --> 54321
def reverse(n):
s=list(str(n))
length = len(s)
r_index = length-1
for index, v in enumerate(s):
if index >= r_index:
break
s[index], s[r_index] = s[r_index], s[index]
r_index -= 1
return int(''.join(s))
def reverse_recurse(n, res=None):
if n/10==0:
return res
if res:
res = res*10 + n%10
else:
res = n%10
return reverse_tail_recurse(n/10, res)
def reverse_tail_recurse(n, res=None):
#print(n, res)
if res:
res = res*10 + n%10
else:
res = n%10
if n/10==0:
return res
return reverse_tail_recurse(n/10, res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment