Given a 32-bit signed integer, reverse digits of an integer.
Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
The input is a signed integer
Max 32 bit signed integer is But more efficient is using constant - 0x7FFFFFFF
Can it be converted to string and then converted back to integer
I bet this has some easy solution using bit manipulation But i hate bit manipulation
Let s go ahead with converting to string and back to integer We can maintain the sign in a variable
If the number is single digit we can just return it
Math.abs(x) is important because we are maintaining the sign separately
+revStr is a cool trick to convert string back to integer
str.reverse() can make this much more cleaner. But, I like to write my own logic for reverse. It’s better to do it this way in the interviews.
This may not be the optimal solution. And that’s okay. The purpose here is to practice problem solving and have fun with algorithms. I am constantly learning new optimized solutions for these problems.
Please comment below if you have a better solution. Let’s learn algorithms and data structures together.