Difficulty: Easy | Acceptance: 82.20% | Paid: No Topics: Math
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.
- Examples
- Constraints
- Direct Simulation Approach
- Mathematical Observation Approach
Examples
Input: num = 526
Output: true
Explanation: Reverse num to get 625, then reverse 625 to get 526, which equals num.
Input: num = 1800
Output: false
Explanation: Reverse num to get 81, then reverse 81 to get 18, which does not equal num.
Input: num = 0
Output: true
Explanation: Reverse num to get 0, then reverse 0 to get 0, which equals num.
Constraints
0 <= num <= 10⁶
Direct Simulation Approach
Intuition Simulate the reversal process twice and compare the final result with the original number.
Steps
- Create a helper function to reverse a number by extracting digits from right to left
- Reverse the original number once to get reversed1
- Reverse reversed1 to get reversed2
- Return true if reversed2 equals the original number, false otherwise
python
class Solution:
def isSameAfterReversals(self, num: int) -> bool:
def reverse(n):
rev = 0
while n > 0:
rev = rev * 10 + n % 10
n //= 10
return rev
reversed_once = reverse(num)
reversed_twice = reverse(reversed_once)
return reversed_twice == num
Complexity
- Time: O(log n) - number of digits in num
- Space: O(1) - only using constant extra space
- Notes: Straightforward implementation but does unnecessary work
Mathematical Observation Approach
Intuition A number remains unchanged after double reversal only if it is 0 or doesn’t end with 0, since trailing zeros become leading zeros and are dropped.
Steps
- Check if the number is 0 (special case that always returns true)
- Check if the last digit is not 0 using modulo operation
- Return true if either condition is met
python
class Solution:
def isSameAfterReversals(self, num: int) -> bool:
# A number is the same after double reversal if:
# 1. It is 0, or
# 2. It doesn't end with 0
return num == 0 or num % 10 != 0
Complexity
- Time: O(1) - constant time operations
- Space: O(1) - no extra space used
- Notes: Optimal solution with minimal computation