Problem Description
You are given an integer num.
Reverse it to get reversed1, then reverse reversed1 to get reversed2.
Return true if reversed2 equals the original number num.
Otherwise return false.
Reversing an integer means reversing all its digits.
For example, reversing 2021 gives 1202.
Reversing 12300 gives 321, since leading zeros are not kept.
Constraints
numis in the range from 0 to 106
Examples
Input: num = 526
Answer: true
Solution
First, let's create a helper function reverse that reverses the number passed to it.
Intuitively, to reverse a number we need to take its last digit and move it to the front. We repeat this trick until the whole number is reversed.
Getting the last digit is very easy: it's the remainder of dividing the number by ten. And we get the "left" part by keeping only the integer part of dividing the number by 10.
right = x % 10;
left = x / 10;So for x = 123 we get the following values.
right = 3;
left = 12;Turning the last digit into the first one is a bit trickier.
Let's create a variable res that starts at 0 and holds the resulting number.
To make the last digit the first one in our result, we just add right to res.
res = res + right;So after the first iteration we have the following values.
left = 12;
right = 3;
res = 3;Now we repeat the computation: extract the new left part and the last digit.
left = 1;
right = 2;
res = 3;If we now simply add the right digit to res, we get 3 + 2 = 5, which is wrong.
We need the added digit to take the next position.
To do that, we first multiply res by 10.
This gives us 30 instead of 3, and adding 2 yields 32, which is the correct sequence.
So the correct formula for res looks like this.
res = res * 10 + right;We do one more iteration and get the final values.
left = 0;
right = 1;
res = 321;As we can see, after processing the last digit left is always 0, so we keep looping while left != 0.
const reverse = (num: number): number => {
let res = 0;
while (num != 0) {
const right = num % 10;
num = Math.floor(num / 10);
res = res * 10 + right;
}
return res;
};Now, with the helper function ready, all we need to do is reverse the original number twice and compare the result.
const reverse = (num: number): number => {
let res = 0;
while (num != 0) {
const right = num % 10;
num = Math.floor(num / 10);
res = res * 10 + right;
}
return res;
};
export const isSameAfterReversals = (num: number): boolean => {
const reversed1 = reverse(num);
const reversed2 = reverse(reversed1);
return num == reversed2;
};Complexity Analysis
Time Complexity
To reverse a number we perform k iterations, where k is the number of digits, which is roughly log(x).
We reverse twice, but the factor of 2 is dropped, so the complexity is O(log(x)).
Space Complexity
O(1): the additional memory is constant.