# A Number After a Double Reversal
**Difficulty:** EASY
[External](https://leetcode.com/problems/a-number-after-a-double-reversal)
Canonical: https://scaleengineer.com/dsa/problems/a-number-after-a-double-reversal
**Patterns:** [Math](https://scaleengineer.com/dsa/patterns/math)
---
## 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 `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 <= 106`

# Approaches
## Simulation using String Conversion
This approach directly simulates the process described in the problem statement. It involves converting the number to a string, reversing it, converting it back to an integer, and repeating the process. The final result is then compared with the original number.
**Time:** O(log10(num)) · **Space:** O(log10(num))
**Pros:** The logic is very straightforward and easy to follow as it directly mirrors the problem description.; It leverages powerful built-in Java library functions, which can make the code concise.
**Cons:** This is the least efficient approach due to the overhead of object creation (String, StringBuilder) and type conversions.; It consumes more memory compared to purely mathematical solutions.
### Explanation
This method translates the problem's logic into code in the most literal way. We create a helper function that performs the reversal of a single number. This function first converts the integer to a `String`. Then, it uses a `StringBuilder` to easily reverse the sequence of characters. Finally, it parses the reversed string back into an integer. The `Integer.parseInt()` method conveniently ignores any leading zeros, which perfectly matches the problem's requirement (e.g., reversing `12300` gives `321`, and parsing the string `"00321"` would also yield `321`). The main function then orchestrates this process, calling the reversal function twice and comparing the final number with the original.

```java
class Solution {
    public boolean isSameAfterReversals(int num) {
        int reversed1 = reverse(num);
        int reversed2 = reverse(reversed1);
        return reversed2 == num;
    }

    private int reverse(int n) {
        String s = Integer.toString(n);
        StringBuilder sb = new StringBuilder(s);
        sb.reverse();
        return Integer.parseInt(sb.toString());
    }
}
```
### Algorithm
1. Define a helper function `reverse(int n)` that takes an integer and returns its reversed form.
2. Inside the helper function:
    a. Convert the integer `n` to its string representation.
    b. Create a `StringBuilder` from the string.
    c. Use the `reverse()` method of `StringBuilder`.
    d. Convert the reversed `StringBuilder` back to a string.
    e. Parse the string back into an integer. This step automatically handles the dropping of leading zeros.
3. In the main function `isSameAfterReversals(int num)`:
    a. Call the helper function to get the first reversal: `reversed1 = reverse(num)`.
    b. Call the helper function again on the result to get the second reversal: `reversed2 = reverse(reversed1)`.
    c. Compare `reversed2` with the original `num` and return `true` if they are equal, `false` otherwise.

## Simulation using Mathematical Operations
This approach also simulates the double reversal process but avoids the overhead of string conversions by using arithmetic operations (modulo and division) to reverse the number. This is generally faster and more memory-efficient.
**Time:** O(log10(num)) · **Space:** O(1)
**Pros:** More efficient in both time and space compared to the string-based approach.; Avoids the overhead of creating and garbage-collecting string and builder objects.
**Cons:** While more efficient than the string approach, it still performs a full simulation which is unnecessary.; The logic for reversing a number mathematically can be slightly more complex to write than using string manipulation.
### Explanation
Instead of converting the number to a string, we can manipulate it directly using mathematics. A helper function for reversal can be implemented by repeatedly taking the last digit of the number and building a new, reversed number. For example, to reverse `526`, we first take `6`, then `2`, then `5`. We build the new number as `(0*10 + 6) = 6`, then `(6*10 + 2) = 62`, and finally `(62*10 + 5) = 625`. This method correctly handles the 'leading zero' issue because the number is built mathematically, so trailing zeros in the original number are simply not carried over. The main function then uses this mathematical `reverse` function twice, just like in the first approach.

```java
class Solution {
    public boolean isSameAfterReversals(int num) {
        int reversed1 = reverse(num);
        int reversed2 = reverse(reversed1);
        return reversed2 == num;
    }

    private int reverse(int n) {
        int reversedNum = 0;
        while (n > 0) {
            int digit = n % 10;
            reversedNum = reversedNum * 10 + digit;
            n /= 10;
        }
        return reversedNum;
    }
}
```
### Algorithm
1. Define a helper function `reverse(int n)` that uses arithmetic to reverse an integer.
2. Inside the helper function:
    a. Initialize a variable `reversedNum` to `0`.
    b. Loop as long as `n` is greater than `0`.
    c. In each iteration, extract the last digit of `n` using the modulo operator (`digit = n % 10`).
    d. Append this digit to `reversedNum` by multiplying `reversedNum` by 10 and adding the `digit`.
    e. Remove the last digit from `n` using integer division (`n /= 10`).
    f. Return `reversedNum` after the loop finishes.
3. In the main function `isSameAfterReversals(int num)`:
    a. Call `reverse(num)` to get `reversed1`.
    b. Call `reverse(reversed1)` to get `reversed2`.
    c. Return the boolean result of `reversed2 == num`.

## O(1) Logical Check
The most efficient approach is derived from a key observation about the reversal process. A number fails the double-reversal test if and only if it has trailing zeros (and is not zero itself). This allows us to solve the problem with a simple check, avoiding any actual reversal operations.
**Time:** O(1) · **Space:** O(1)
**Pros:** Extremely efficient, providing a solution in constant time and constant space.; The code is minimal, simple, and elegant.
**Cons:** The solution is not immediately obvious and requires a logical deduction about the properties of the reversal operation rather than a direct simulation.
### Explanation
By analyzing the problem, we can find a much faster solution. The core of the problem lies in whether information is lost during the first reversal. When we reverse a number like `526`, we get `625`. No information is lost. Reversing it again gives `526`. However, when we reverse `1800`, the trailing zeros become leading zeros and are dropped, resulting in `81`. The information about the trailing zeros is lost forever. Reversing `81` gives `18`, which doesn't equal the original `1800`.

The only case where a number ends in zero but passes the test is `num = 0` itself. For any other number `num > 0`, if it ends in a zero (`num % 10 == 0`), the double reversal will not yield the original number. If it does not end in a zero, it will.

This leads to a very simple and efficient check:
the number is the same after a double reversal if and only if the number is `0` or it does not end in `0`.

```java
class Solution {
    public boolean isSameAfterReversals(int num) {
        // If num is 0, it remains 0 after double reversal.
        // If num is non-zero and ends in 0 (e.g., 1800), the trailing zero is lost
        // in the first reversal (1800 -> 81), so it can't be recovered.
        // If num does not end in 0, no information is lost.
        return num == 0 || num % 10 != 0;
    }
}
```
### Algorithm
1. Analyze the effect of the double reversal.
2. The first reversal `reverse(num)` loses information only if `num` has trailing zeros (which become leading zeros and are dropped). For example, `reverse(1800)` is `81`.
3. If information is lost in the first step, the second reversal cannot restore the original number. `reverse(81)` is `18`, which is not `1800`.
4. The only exception is `num = 0`. `reverse(0)` is `0`, so it passes the test.
5. Therefore, a number will fail the test if and only if it is a non-zero number that ends in `0`.
6. The logic simplifies to: return `true` if `num` is `0` or if its last digit is not `0`.
7. This can be implemented with the expression `num == 0 || num % 10 != 0`.

# Solutions
### Java

```java
class Solution {
public
  boolean isSameAfterReversals(int num) { return num == 0 || num % 10 != 0; }
}

```

### JavaScript

```javascript
/** * @param {number} num * @return {boolean} */ var isSameAfterReversals =
  function (num) {
    return num === 0 || num % 10 !== 0;
  };

```

### CPP

```cpp
class Solution {
public:
  bool isSameAfterReversals(int num) { return num == 0 || num % 10 != 0; }
};

```

### Python

```python
class Solution:
    def isSameAfterReversals(
        self, num: int) -> bool: return num == 0 or num % 10 != 0

```
