A Number After a Double Reversal - Problem

Imagine you have a number and you decide to reverse its digits twice. Will you get back to the original number?

When we reverse an integer, we flip all its digits from right to left. For example:

  • Reversing 2021 gives us 1202
  • Reversing 12300 gives us 321 (leading zeros disappear!)

The Challenge: Given an integer num, perform these operations:

  1. Reverse num to get reversed1
  2. Reverse reversed1 to get reversed2
  3. Check if reversed2 equals the original num

Return true if they're equal, false otherwise.

This problem tests your understanding of number manipulation and the behavior of leading zeros!

Input & Output

example_1.py โ€” Basic Case
$ Input: num = 526
โ€บ Output: true
๐Ÿ’ก Note: 526 โ†’ 625 โ†’ 526. The number returns to its original form because it doesn't end with zero, so no digits are lost during reversal.
example_2.py โ€” Trailing Zero Case
$ Input: num = 1800
โ€บ Output: false
๐Ÿ’ก Note: 1800 โ†’ 0081 โ†’ 81. The trailing zeros become leading zeros in the first reversal and disappear, so we get 81 โ‰  1800.
example_3.py โ€” Special Case Zero
$ Input: num = 0
โ€บ Output: true
๐Ÿ’ก Note: 0 โ†’ 0 โ†’ 0. Zero remains zero after any number of reversals, so it always returns true.

Visualization

Tap to expand
Why Trailing Zeros MatterSuccess Case: 123123321123โœ“ 123 = 123No digits lost!Failure Case: 12012002121โœ— 120 โ‰  21Leading zero disappears!Key InsightCheck if num % 10 == 0(Special case: 0 โ†’ true)
Understanding the Visualization
1
Normal Number
Numbers without trailing zeros (like 123) reverse cleanly: 123 โ†’ 321 โ†’ 123
2
Trailing Zero Issue
Numbers with trailing zeros (like 120) lose digits: 120 โ†’ 021 โ†’ 21
3
Pattern Recognition
Only need to check if the last digit is zero to determine the result
Key Takeaway
๐ŸŽฏ Key Insight: A number survives double reversal if and only if it doesn't end with zero (except 0 itself), because trailing zeros become leading zeros and disappear!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(log n)

We process each digit of the number twice, where the number of digits is logโ‚โ‚€(n)

n
2n
โšก Linearithmic
Space Complexity
O(1)

Only using a constant amount of extra variables

n
2n
โœ“ Linear Space

Constraints

  • 0 โ‰ค num โ‰ค 106
  • Leading zeros are dropped during reversal
  • The input is always a valid non-negative integer
Asked in
Amazon 15 Google 12 Microsoft 8 Meta 6
28.7K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen