A Number After a Double Reversal Problem
#2119
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2119.
Reversing an integer means to reverse all its digits.
- For example, reversing
2021gives1202. Reversing12300gives321as 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.
Example 1:
Input: num = 526
Output: true
Explanation: Reverse num to get 625, then reverse 625 to get 526, which equals num.
Example 2:
Input: num = 1800
Output: false
Explanation: Reverse num to get 81, then reverse 81 to get 18, which does not equal num.
Example 3:
Input: num = 0
Output: true
Explanation: Reverse num to get 0, then reverse 0 to get 0, which equals num.
Constraints:
0 <= num <= 10^6
Solution
Approach: Mathematics
Reversing drops trailing zeros: 1800 becomes 81 and then 18. So the number comes back unchanged exactly when it has no trailing zero, that is, when num is 0 or its last digit is not 0.
Complexity: time O(1); space O(1).
class Solution:
def isSameAfterReversals(self, num: int) -> bool:
return num == 0 or num % 10 != 0