Reverse Number Using Recursion in Java
Problem
Reversing a number's digits recursively means peeling off one digit per call and folding it into an accumulator that's passed down to the next call, instead of building the result in a loop.
Given a number, reverse the order of its digits using recursion.
Java Program
public class ReverseNumberRecursion {
static int reverse(int n, int result) {
if (n == 0) return result; // every digit has been moved into result
return reverse(n / 10, result * 10 + n % 10);
}
public static void main(String[] args) {
int n = 1234;
System.out.println("Reversed number: " + reverse(n, 0));
}
}Output
Core Logic
Passing the partially-built reversed number down as a second argument lets each call add one more digit without needing to return and recombine anything on the way back up.
- 1
reverse(n, result)takes both the remaining digits ofnand the reversed value built so far inresult. - 2Each call peels off
n's last digit withn % 10, shiftsresultone place left withresult * 10, and adds the digit in. - 3The next call receives
n / 10(one digit shorter) and the updatedresult. - 4The base case
if (n == 0) return result;fires once every digit has been moved over, returning the finished value directly — no unwinding step needed.
1234, the digits 4, 3, 2, 1 are folded into result in that order — 4, then 43, then 432, then 4321 — and the base case returns 4321 as soon as n reaches 0.Key Point: Because the accumulator carries the answer forward instead of being combined after the recursive call returns, the result is already correct the moment the base case fires — there's nothing left to do on the way back up the stack.
Why: One recursive call handles one digit, so the call count and the stack depth both equal the number's digit count d.