I'm practicing some python exercise and I have some doubts about the solution of reversing a number. Example, 42 -> 24, -314 -> -413.
The book has this solution:
def reverse(x: int) -> int: result, x_remaining = 0, abs(x) while x_remaining: result = result * 10 + x_remaining % 10 x_remaining //= 10 return -result if x < 0 else result
def reverse_digit(x: int) -> int: s = str(abs(x)) result = s[::-1] if x >= 0: return int(result) else: return int("-" + 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)?