algoadvance

Leetcode 2119. A Number After a Double Reversal

Problem Statement

Given an integer num, return true if num can be reversed twice and still be equal to num. Otherwise, return false.

Constraints:

For example:

Clarifying Questions

  1. Are negative numbers a part of input?
    • No, as per the constraints the number is between 0 and 10^6.
  2. Do we have to handle large integers, or can int in C++ handle all values within the provided constraints?
    • int in C++ is sufficient since it can handle values up to a bit over 2 billion, well beyond the constraint of 10^6.

Strategy

The strategy here hinges on understanding the reversal process:

  1. When a number is reversed, all non-zero digits are rearranged such that the number reads backward.
  2. If this reversed number is reversed again, the number returns to its original form, provided it does not have any leading zeros (in other words, trailing zeros in the original number).

The only situation where a number will not be the same after a double reversal is if it has trailing zeros. For example, 100 reversed becomes 001 (1), and reversing 1 gives 1, which is not equal to the original number (100).

From this, we can infer:

Code

Here’s an implementation in C++:

class Solution {
public:
    bool isSameAfterReversals(int num) {
        // if num is 0, it's always true
        if (num == 0) return true;
        // if the number has trailing zero, it will fail
        return num % 10 != 0;
    }
};

Time Complexity

The time complexity of this solution is O(1) because:

This ensures the solution is very efficient and runs in constant time regardless of the input’s size.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI