A Number After a Double Reversal (LeetCode 2119): Solution and Explanation
Decide whether reversing the digits of num twice gives num back, given that reversal drops leading zeros.
Intuition
Reversing digits is its own inverse as long as no digit gets lost along the way. The only digits that can get lost are leading zeros of the reversed number.
The leading zeros of reversed1 are exactly the trailing zeros of num. So 1800 becomes 0081, which is just 81, and the two zeros are gone for good.
Zeros in the middle, like the 0 in 101, stay between nonzero digits and survive. The whole question collapses to one check on the last digit, with 0 itself as the only special case.
Approach: Check the last digit
- If num is 0, return true: 0 reverses to 0.
- Otherwise return whether num % 10 is not 0.
Step-by-step example
num = 1800
- num is not 0, so look at the last digit: 1800 % 10 = 0.
- To see why that matters: the first reversal writes 0081, and the leading zeros are dropped, giving 81.
- The second reversal turns 81 into 18.
- 18 != 1800, matching num % 10 != 0 being false. Return false.
Code: Python, Java, C++
1class Solution:
2 def isSameAfterReversals(self, num: int) -> bool:
3 if num == 0:
4 return True
5 return num % 10 != 01class Solution {
2 public boolean isSameAfterReversals(int num) {
3 if (num == 0) {
4 return true;
5 }
6 return num % 10 != 0;
7 }
8}1class Solution {
2public:
3 bool isSameAfterReversals(int num) {
4 if (num == 0) {
5 return true;
6 }
7 return num % 10 != 0;
8 }
9};Time and space complexity
O(1)
One comparison and one modulo, independent of the number of digits.
O(1)
No extra storage.
Other approaches
Simulate both reversals (time O(d), space O(1))
Reverse num with a digit loop (or a string), reverse the result again and compare with num. Correct and easy to trust, just more work than needed.
Common mistakes
- Returning false for num = 0. Its last digit is 0, but there is nothing to lose: 0 reverses to 0.
- Thinking any zero digit breaks it. Only trailing zeros are lost; 101 and 909091 survive.
- Reversing through a string and forgetting to strip leading zeros, which makes every input look like it survives.
Frequently asked questions
Why does 0 need its own case?
0 % 10 is 0, so the general rule would say false. But 0 is written with a single digit and reversing it gives 0 again, so the answer is true.
Can overflow happen when simulating?
Not here, since num is at most 10^6. For values near the 32-bit limit, reversing could overflow, which is one more reason to prefer the last-digit check.