Created
December 26, 2018 07:37
-
-
Save o3o3o/42af0b3dea6cea38d1630c65ba07e214 to your computer and use it in GitHub Desktop.
reverse integers with tail recurse
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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