I'm grinding some LeetCode stuff, and one of the problems was to reverse an integer's digits (e.g. 123 becomes 321).
I thought of 2 ways to do it. The first is purely "numeric", using powers of 10 and modular arithmetic:
def reverse_digits1(num):
reversed_num = 0
while num > 0:
reversed_num *= 10
reversed_num += num % 10
num = num // 10
return reversed_num
The second way is to use built-in str() and int() methods.
def reverse_digits2(num):
num = str(num)
return int(num[::-1])
You essentially convert it to a string, reverse it, then return the reversed string as an integer.
Between these 2, which is the "better" way to do it? I'm guessing it's the first one, and it doesn't involve mutating numbers into strings and vice versa, and there is no potential loss of information? Would there even be a loss of information? The inputs are all integers, so there's no floating point numbers to worry about, right?
In general, is it a good idea to work with numbers through str() and int(), or should you just stick to "numerical methods"?
I added negatives just in case you may need them but the overall performance wouldn't change drastically without them either.
def reverse_digits1(num):
if num < 0:
neg = True
else:
neg = False
if neg:
num *= -1
reversed_num = 0
while num > 0:
reversed_num *= 10
reversed_num += num % 10
num = num // 10
if neg:
reversed_num *= -1
return reversed_num
def reverse_digits2(num):
num = str(num)[::-1]
if num.endswith('-'):
num = '-' + num[:-1]
return int(num)
from timeit import timeit as _t
timeit = lambda x: print(_t(x, globals=globals()))
timeit("reverse_digits1(123456789)")
timeit("reverse_digits1(-123456789)")
timeit("reverse_digits2(123456789)")
timeit("reverse_digits2(-123456789)")
This result in
5.207313711074936
6.272431325012982
2.453335871448827
3.285427497418125
So other than being more readable* it actually is also faster.
As of the information loss, I can't imagine it being possible with your regular integers, and even if it was floats or some other type of number, strings would be more reliable since as a very basic example, 0.1+02 == 0.300000000000001, in strings however you can manipulate them with certain precision.
*Keep in mind, code is written to be read by humans.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With