Reversing Digits

September 4, 2015

After Tuesday’s exercise on Lychrel numbers, I answered a question about Lychrel numbers over at Stack Overflow, using a recursive function to extract and reverse the digits one-by-one. I was challenged by a reader who claimed “using int("".join(reversed(str(n)))) has got to be far more efficient than using your recursive function. Your function is clever, but clever isn’t always best.” He was wrong, of course: arithmetic on numbers is better than converting a number to a string, creating a generator to reverse the individual characters of the string, appending them one-by-one to a new string, and converting the new string back to a number, which I demonstrated to him in a timing experiment.

Your task is to find the best way to reverse the digits of a positive integer, in the language of your choice. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Advertisement

Pages: 1 2