Leetcode 2119. A Number After a Double Reversal
Given an integer num, return true if num can be reversed twice and still be equal to num. Otherwise, return false.
0 <= num <= 10^6For example:
num = 526trueExplanation: Reversing 526 gives 625. Reversing 625 gives 526, which is the original number.
num = 0trueint 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.The strategy here hinges on understanding the reversal process:
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:
true if num is 0.num % 10 != 0.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;
}
};
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.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?