Member-only story

Leetcode 2119: A Number After a Double Reversal

Pierre-Marie Poitevin
2 min readJan 2, 2022

--

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 gives 1202. Reversing 12300 gives 321 as the leading zeros are not retained.

Given an integer num, reverse num to get reversed1, then reverse reversed1 to get reversed2. Return true if reversed2 equals num. Otherwise return false.

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:

Decision tree

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!

--

--

Pierre-Marie Poitevin
Pierre-Marie Poitevin

No responses yet