Solution discussion on the best way to reverse a number in Python I'm practicing some python exercise and I have some doubts about the solution of reversing a number. Example, 42 -&gt; 24, -314 -&gt; -413.
The book has this solution:

def reverse(x: int) -&gt; int:
  result, x_remaining = 0, abs(x)
  while x_remaining:
      result = result * 10 + x_remaining % 10
      x_remaining //= 10
  return -result if x &lt; 0 else result


My solution:
def reverse_digit(x: int) -&gt; int:
  s = str(abs(x))
  result = s[::-1]
  if x &gt;= 0:
    return int(result)
  else:
    return int(&quot;-&quot; + result)

The book says that converting the number to string would be a brute-force solution but don't they have the same time complexity, O(n)?
Is the book solution that much better than mine (that in my opinion is much simpler and easy to read)?
First, a note on complexity. Both your implementation and the reference implementation do indeed have O(n) complexity in the number of input digits in the best case, but O(log(n)) in the range of the input number.
This depends, mind you, on the expected range of the input number. For &quot;typical values&quot; below the limit of machine precision, which these days will be \$2^{63}\$ for most people, the contents of the reference implementation's inner loop will be constant-time. However, Python has automatic support for arbitrary precision, and if that support is used, the reference implementation will end up being super-linear in the worst case.
As for reversal of a negative number, I think it makes less sense to automatically abs() than just to raise, because - if you interpret the number as a string - negative numbers are non-reversible. I say this knowing that it violates the reference implementation if you interpret it as a specification, but I don't think the specification makes much sense.