A Number After a Double Reversal
EasyPrompt
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 <= 106
Approaches
3 approaches with complexity analysis and trade-offs.
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.
Algorithm
- Define a helper function
reverse(int n)that takes an integer and returns its reversed form. - Inside the helper function:
a. Convert the integer
nto its string representation. b. Create aStringBuilderfrom the string. c. Use thereverse()method ofStringBuilder. d. Convert the reversedStringBuilderback to a string. e. Parse the string back into an integer. This step automatically handles the dropping of leading zeros. - 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. Comparereversed2with the originalnumand returntrueif they are equal,falseotherwise.
Walkthrough
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.
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()); }}Complexity
Time
O(log10(num))
Space
O(log10(num))
Trade-offs
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.
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.
Algorithm
- Define a helper function
reverse(int n)that uses arithmetic to reverse an integer. - Inside the helper function:
a. Initialize a variable
reversedNumto0. b. Loop as long asnis greater than0. c. In each iteration, extract the last digit ofnusing the modulo operator (digit = n % 10). d. Append this digit toreversedNumby multiplyingreversedNumby 10 and adding thedigit. e. Remove the last digit fromnusing integer division (n /= 10). f. ReturnreversedNumafter the loop finishes. - In the main function
isSameAfterReversals(int num): a. Callreverse(num)to getreversed1. b. Callreverse(reversed1)to getreversed2. c. Return the boolean result ofreversed2 == num.
Walkthrough
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.
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; }}Complexity
Time
O(log10(num))
Space
O(1)
Trade-offs
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.
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.
Algorithm
- Analyze the effect of the double reversal.
- The first reversal
reverse(num)loses information only ifnumhas trailing zeros (which become leading zeros and are dropped). For example,reverse(1800)is81. - If information is lost in the first step, the second reversal cannot restore the original number.
reverse(81)is18, which is not1800. - The only exception is
num = 0.reverse(0)is0, so it passes the test. - Therefore, a number will fail the test if and only if it is a non-zero number that ends in
0. - The logic simplifies to: return
trueifnumis0or if its last digit is not0. - This can be implemented with the expression
num == 0 || num % 10 != 0.
Walkthrough
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.
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; }}Complexity
Time
O(1)
Space
O(1)
Trade-offs
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.
Solutions
Solution
class Solution {public boolean isSameAfterReversals(int num) { return num == 0 || num % 10 != 0; }}/** * @param {number} num * @return {boolean} */ var isSameAfterReversals = function (num) { return num === 0 || num % 10 !== 0; };class Solution {public: bool isSameAfterReversals(int num) { return num == 0 || num % 10 != 0; }};class Solution: def isSameAfterReversals( self, num: int) -> bool: return num == 0 or num % 10 != 0Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.