Java ProgramsRecursionReverse Number Using Recursion

Reverse Number Using Recursion in Java

beginner·  Recursion  ·  Recursion

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.

Input
1234
Output
Reversed number: 4321

Java Program

Java
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

Reversed number: 4321

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.

How It Works
  1. 1reverse(n, result) takes both the remaining digits of n and the reversed value built so far in result.
  2. 2Each call peels off n's last digit with n % 10, shifts result one place left with result * 10, and adds the digit in.
  3. 3The next call receives n / 10 (one digit shorter) and the updated result.
  4. 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.
For 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.

Complexity
Time Complexity: O(d)Space Complexity: O(d)

Why: One recursive call handles one digit, so the call count and the stack depth both equal the number's digit count d.

Key Concepts

recursionaccumulator parameterbase case

Related Programs