LeetCode Reverse Integer Solution
The Reverse Integer problem on LeetCode is quite popular with several dislikes due to weird edge cases, however a great problem to mess around with simple integer math.
Note: I don’t solve this completely handling the edge cases of not being able to store 64 bit integers. I saw the solution and just felt that the problem was testing if I had that type of knowledge rather than general problem solving with coding.
Problem
Given an integer x
return the value x
with the digits reversed.
So like most of these problems it requires knowing 1–2 tricks, if you don’t know them I wouldn’t sweat it. Before reading on, the only hint I’ll give is that any integer manipulation either requires converting to a string or use the base of the value (in this case 10).
Solution
So I personally didn’t want to deal with negative numbers at the start, so I decided to multiply by the -1 to make x
positive then set a boolean to track if the value is negative.
Here’s the code snippet I’m starting with:
is_negative = False
if x < 0:
is_negative = True
x *= -1
Next is to solve the base logic of this, for example the value 245, how do we get the reverse of this value?