Member-only story
Leetcode 2119: A Number After a Double Reversal
In this problem, we are asked if a number will be the same if we reverse its digits twice.
Reversing an integer means to reverse all its digits.
For example, reversing
2021
gives1202
. Reversing12300
gives321
as the leading zeros are not retained.Given an integer
num
, reversenum
to getreversed1
, then reversereversed1
to getreversed2
. Returntrue
ifreversed2
equalsnum
. Otherwise returnfalse
.
For example
123 -> 321 -> 123; we should return "true" for 123.
120 -> 21 -> 12; we should return "false" for 120.
0 -> 0 -> 0; we should return "true" for 0.
We can see intuitively that the only case in which the int will change is if they end with 0, in which case the 0 will be removed after the double reversal, and the only exception is with “0”, which is an edge case.
This gives us a decision tree for our algorithm:
If the number is 0 we return true. Otherwise, we want to know if the number ends with 0. If yes, then return false, else return true.
This algorithm can be converted in code easily, this is the code in C for example:
bool isSameAfterReversals(int num){
if (num == 0) {
return true;
}
return (num % 10 != 0);
}
The exact same code will solve the problem in Java
class Solution {
public boolean isSameAfterReversals(int num) {
if (num == 0) {
return true;
}
return (num % 10 != 0);
}
}
Happy coding!
I give algorithms and coding prep lessons, DM me!