Problem

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 numreverse num to get reversed1then reverse reversed1 to get reversed2. Return true if reversed2 equals num. Otherwise return false.

Examples

Example 1:

1
2
3
4
5
Input:
num = 526
Output:
 true
Explanation: Reverse num to get 625, then reverse 625 to get 526, which equals num.

Example 2:

1
2
3
4
5
Input:
num = 1800
Output:
 false
Explanation: Reverse num to get 81, then reverse 81 to get 18, which does not equal num.

Example 3:

1
2
3
4
5
Input:
num = 0
Output:
 true
Explanation: Reverse num to get 0, then reverse 0 to get 0, which equals num.

Solution

Method 1 – Mathematical Observation

Intuition

Reversing a number removes trailing zeros. If a number has no trailing zeros or is zero, double reversal returns the original number. Otherwise, the number changes after double reversal.

Approach

  1. If num is 0, return true.
  2. If num has no trailing zeros (num % 10 != 0), return true.
  3. Otherwise, return false.

Code

1
2
3
4
5
6
class Solution {
public:
    bool isSameAfterReversals(int num) {
        return num == 0 || num % 10 != 0;
    }
};
1
2
3
func isSameAfterReversals(num int) bool {
    return num == 0 || num%10 != 0
}
1
2
3
4
5
class Solution {
    public boolean isSameAfterReversals(int num) {
        return num == 0 || num % 10 != 0;
    }
}
1
2
3
4
5
class Solution {
    fun isSameAfterReversals(num: Int): Boolean {
        return num == 0 || num % 10 != 0
    }
}
1
2
3
class Solution:
    def isSameAfterReversals(self, num: int) -> bool:
        return num == 0 or num % 10 != 0
1
2
3
4
5
impl Solution {
    pub fn is_same_after_reversals(num: i32) -> bool {
        num == 0 || num % 10 != 0
    }
}
1
2
3
4
5
class Solution {
    isSameAfterReversals(num: number): boolean {
        return num === 0 || num % 10 !== 0;
    }
}

Complexity

  • ⏰ Time complexity: O(1), only a constant number of operations.
  • 🧺 Space complexity: O(1), only a constant amount of extra space is used.