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"?