Last active
October 19, 2017 16:30
-
-
Save SteadBytes/0a14d1a3effdbdd01d1728a2b73eafdc to your computer and use it in GitHub Desktop.
Mathematical and String-based methods for reversing the digits of an integer
This file contains 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
import timeit | |
# reverse the digits of an integer i.e 1234 -> 4321 | |
# String method turns out to be faster! (timer code if if __name__=='main' section) | |
def reverse_int_math(x): | |
"""Reverses the digits of an integer mathematically | |
Args: | |
x (int): integer to reverse | |
Returns: | |
int: x reversed | |
""" | |
reverse = 0 | |
while x > 0: | |
last_digit = x % 10 | |
# *10 to 'make space' for last_digit | |
reverse = (reverse * 10) + last_digit | |
x //= 10 | |
return reverse | |
def reverse_int_string(x): | |
"""Reverses the digits of an integer by casting to a string, reversing, | |
then casting back to an int. | |
Args: | |
x (int): integer to reverse | |
Returns: | |
int: x reversed | |
""" | |
return int(str(x)[::-1]) | |
def reverse_int_binary(x): | |
"""Reverses the digits of an integer by casting to a string, reversing, | |
then casting back to an int. | |
Args: | |
x (int): integer to reverse | |
Returns: | |
int: x reversed | |
""" | |
res = 0 | |
while x > 0: | |
res = res << 1 | |
res = res | (x & 1) | |
x = x >> 1 | |
return res | |
if __name__ == '__main__': | |
print('Mathematical method:') | |
print(timeit.timeit('reverse_int_math(123456723452346547457)', | |
setup='from __main__ import reverse_int_math')) | |
print('String method:') | |
print(timeit.timeit('reverse_int_string(123456723452346547457)', | |
setup='from __main__ import reverse_int_string')) | |
print('Binary method:') | |
print(timeit.timeit('reverse_int_binary(123456723452346547457)', | |
setup='from __main__ import reverse_int_binary')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment