Add a Number to Its Reverse
Solve this ProblemEasy10 min
Topics
BasicsFunctionsMath
Companies
TCSInfosysWipro
Given a non-negative integer
n, return n plus its digit-reversal. For example, 123 + 321 = 444. Leading zeros created by reversing are dropped, so 120 reverses to 21.
Reversing digits is useful on its own, so it belongs in a helper functionHelper FunctionA small function that does one focused job, such as reverseNumber(n), so the main function can call it by name.. With the helper in place, the main function reads exactly like the problem statement. The two solutions reverse in different ways — through text, or with digit arithmeticDigit ArithmeticUsing % 10 to read the last digit and / 10 to remove it, so a number can be processed digit by digit. — but the main function is identical in both.
Test Case 1:
Input:n = 123
Output:444
Explanation:123 reversed is 321, and 123 + 321 = 444.
Test Case 2:
Input:n = 120
Output:141
Explanation:Reversing 120 gives "021", which is the number 21; 120 + 21 = 141.
Constraints
- ◆
0 ≤ n ≤ 100000000
Try the Dry Run
Approach & Solutions
Reverse Through a StringGood
Write a helper reverseNumber(n) that turns n into text, reverses the characters, and turns the text back into a number (which quietly drops any leading zeros). The main function is then a single line: n + reverseNumber(n). C reverses the characters in its buffer with two indices meeting in the middle.
Time
O(d)Space
O(d)Java
class Solution {
int reverseNumber(int n) {
String reversed = new StringBuilder(String.valueOf(n)).reverse().toString();
return Integer.parseInt(reversed);
}
public int reverseAndAdd(int n) {
return n + reverseNumber(n);
}
}Digit Arithmetic in a HelperOptimal
Reverse the number without any text. Repeatedly take the last digit with n % 10, append it to the reversed value (reversed × 10 + digit), and drop it from n with integer division by 10. Leading zeros never appear because they would be multiplied into the front as 0.
Time
O(d)Space
O(1)Java
class Solution {
int reverseNumber(int n) {
int reversed = 0;
while (n > 0) {
reversed = reversed * 10 + n % 10;
n /= 10;
}
return reversed;
}
public int reverseAndAdd(int n) {
return n + reverseNumber(n);
}
}