October 26, 2020
Hello fellow devs 👋! It’s a new day and it’s time for looking into another LeetCode problem.
Given a 32-bit signed integer, reverse digits of an integer.
Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
-231 <= x <= 231 - 1
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Example 4:
Input: x = 0
Output: 0
This problem is pretty straightforward 😄. To reverse an integer, we only have to make most significant digit as the least significant digit and vice versa, the second most significant digit to the second least significant digit and vice versa and so on.
There are couple of things we need to keep in mind -
The approach is simple -
long
in case of Java/Kotlin)/Since we are going through the entire number digit by digit, the time complexity should be O(log10n). The reason behind log10 is because we are dealing with integers which are base 10.
We are not using any data structure for interim operations, therefore, the space complexity is O(1).
public class ReverseInteger {
public int reverse(int x) {
boolean isNegative = false;
if (x < 0) {
isNegative = true;
x = -x;
}
long reverse = 0;
while (x > 0) {
reverse = reverse * 10 + x % 10;
x /= 10;
}
if (reverse > Integer.MAX_VALUE) {
return 0;
}
return (int) (isNegative ? -reverse : reverse);
}
}
def reverse(x: int) -> int:
isNegative = False
if x < 0:
isNegative = True
x = -x
reversedNumber = 0
while x:
reversedNumber = reversedNumber * 10 + x % 10
x //= 10
if reversedNumber >= 2 ** 31 - 1 or reversedNumber <= -2 ** 31:
return 0
return -reversedNumber if isNegative else reversedNumber
var reverse = function(x) {
let isNegative = false;
if (x < 0) {
isNegative = true;
x = -x;
}
let reverse = 0;
while (x > 0) {
reverse = reverse * 10 + x % 10;
x = parseInt(x / 10);
}
if (reverse >= Math.pow(2, 31) - 1 || reverse <= Math.pow(-2, 31)) {
return 0;
}
return isNegative ? -reverse : reverse;
};
fun reverse(x: Int): Int {
var num = x
var isNegative = false
if (num < 0) {
isNegative = true
num = -num
}
var reverse: Long = 0
while (num > 0) {
reverse = reverse * 10 + num % 10
num /= 10
}
return if (reverse > Int.MAX_VALUE) {
0
} else (if (isNegative) -reverse else reverse).toInt()
}
Today we discussed how to solve LeetCode problem - Reverse integer.
I hope you have enjoyed this post. Feel free to share your thoughts on this.
You can find the complete source code on my GitHub repository. If you like what you learn. feel free to fork 🔪 and star ⭐ it.
Till next time… Happy coding 😄 and Namaste 🙏!