Placement Prep

Reverse a Number in C, C++, Java and Python

Iterative and recursive approaches to reverse a number in C, C++, Java, and Python. Step-by-step trace, working code, and complexity analysis.

By FACE Prep Team 6 min read
number-reversal c-plus-plus java python algorithms placement-prep loops recursion

Reversing a number digit by digit is one of the first loop problems recruiters use to check whether a candidate understands modulo arithmetic and loop control.

The mechanism is three steps repeating: pull the last digit off with % 10, append it to the result using * 10 + rem, and discard the processed digit with / 10. Four or five iterations for a five-digit input. No string conversion required.

Understanding the Problem

Given a positive integer, produce its digit-reversed counterpart.

  • Input: 13579
  • Output: 97531

The key insight is that n % 10 always returns the rightmost digit of any integer n. Pairing that with integer division n / 10 removes that digit from the original. Repeat until nothing is left.

A step-by-step trace of 13579 makes the loop mechanics explicit:

Stepnumrem = num % 10rev = rev * 10 + remnum = num / 10
113579991357
21357797135
3135597513
413397531
511975310

At step 5, num reaches 0 and the loop exits. Result: 97531.

Notice the rev * 10 multiplication in each step. It shifts the already-accumulated digits one place to the left, creating a slot for the newly extracted digit. Without it, each new digit would just overwrite the last.

Two edge cases appear regularly in placement test variants:

  • Single digit: num = 7 — the loop runs once, rem = 7, rev = 7, then num = 0 exits. Correct.
  • Number ending in zero: num = 1200 — the result is 21, not 0021. Integer zero at the front of a number carries no value. If the problem requires preserving the zero, convert to string first.

The Iterative Approach

Algorithm

  • Initialise rev = 0.
  • While num > 0:
    • Extract the last digit: rem = num % 10.
    • Append it to the result: rev = rev * 10 + rem.
    • Discard the last digit: num = num / 10.
  • Return rev.

Complexity:

  • Time: O(log n). The loop runs once per digit, and a number n has approximately log base 10 of n digits.
  • Space: O(1). Two variables, rev and rem, regardless of input size.

C

#include <stdio.h>

int reverseNumber(int num) {
    int rev = 0, rem;
    while (num > 0) {
        rem = num % 10;
        rev = rev * 10 + rem;
        num /= 10;
    }
    return rev;
}

int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    printf("Reversed Number: %d\n", reverseNumber(num));
    return 0;
}

The modulo % and integer division / operators in C and C++ truncate toward zero for positive integers. This truncation is exactly the behaviour the algorithm depends on: 1357 / 10 gives 135, not 135.7.

C++

#include <iostream>
using namespace std;

int reverseNumber(int num) {
    int rev = 0, rem;
    while (num > 0) {
        rem = num % 10;
        rev = rev * 10 + rem;
        num /= 10;
    }
    return rev;
}

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;
    cout << "Reversed Number: " << reverseNumber(num) << endl;
    return 0;
}

The C++ version is structurally identical to the C version. The only change is input/output: cout/cin replaces printf/scanf. The arithmetic logic, loop condition, and variable names stay the same.

Java

import java.util.Scanner;

public class ReverseNumber {
    public static int reverseNumber(int num) {
        int rev = 0, rem;
        while (num > 0) {
            rem = num % 10;
            rev = rev * 10 + rem;
            num /= 10;
        }
        return rev;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = scanner.nextInt();
        System.out.println("Reversed Number: " + reverseNumber(num));
        scanner.close();
    }
}

Java’s / operator on two int values performs integer division, truncating the decimal part. The same algorithm body works without modification.

Python

def reverse_number(num):
    rev = 0
    while num > 0:
        rev = rev * 10 + num % 10
        num //= 10
    return rev

num = int(input("Enter a number: "))
print("Reversed Number:", reverse_number(num))

Python’s floor division operator // always returns an integer by truncating toward negative infinity. For positive values of num, the behaviour matches C/Java integer division exactly: 1357 // 10 gives 135. Using / instead would return 135.7, breaking the loop condition and producing a wrong answer.

The Recursive Approach

Recursion replaces the loop with a helper function that carries the partially built result as an accumulator parameter. Each call handles one digit, then delegates the rest to the next call.

Algorithm

  • Base case: if num == 0, return rev.
  • Extract the last digit: rem = num % 10.
  • Recurse: reverseHelper(num / 10, rev * 10 + rem).

Each call strips one digit from num and appends it to rev. The call depth equals the digit count.

Complexity:

  • Time: O(log n). Same as the iterative approach, one operation per digit.
  • Space: O(log n). One stack frame per digit. A 10-digit number generates 10 live frames before the base case fires.

C

#include <stdio.h>

int reverseHelper(int num, int rev) {
    if (num == 0) return rev;
    return reverseHelper(num / 10, rev * 10 + (num % 10));
}

int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    printf("Reversed Number: %d\n", reverseHelper(num, 0));
    return 0;
}

C++

#include <iostream>
using namespace std;

int reverseHelper(int num, int rev) {
    if (num == 0) return rev;
    return reverseHelper(num / 10, rev * 10 + (num % 10));
}

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;
    cout << "Reversed Number: " << reverseHelper(num, 0) << endl;
    return 0;
}

Java

import java.util.Scanner;

public class ReverseNumber {
    public static int reverseHelper(int num, int rev) {
        if (num == 0) return rev;
        return reverseHelper(num / 10, rev * 10 + (num % 10));
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = scanner.nextInt();
        System.out.println("Reversed Number: " + reverseHelper(num, 0));
        scanner.close();
    }
}

Python

def reverse_helper(num, rev=0):
    if num == 0:
        return rev
    return reverse_helper(num // 10, rev * 10 + num % 10)

num = int(input("Enter a number: "))
print("Reversed Number:", reverse_helper(num))

The Python recursive version uses a default parameter rev=0 so the public API is reverse_helper(num) rather than reverse_helper(num, 0). Both forms work; the default parameter style is more Pythonic.

Comparing Both Approaches

ApproachTime ComplexitySpace ComplexityWhen to Use
IterativeO(log n)O(1)Default choice: simple and memory-efficient
RecursiveO(log n)O(log n)When recursion is explicitly required

Both approaches perform the same computation. The space difference is what matters in practice. The recursive version maintains one stack frame per digit: for a 10-digit number that is 10 live frames versus the two fixed variables in the iterative version.

The iterative version also sidesteps stack-overflow risk on unusually large inputs. Prefer it as the default answer unless the problem statement or interviewer specifically calls for recursion. The same O(1) space preference applies to finding the smallest and largest element in an array, where a single pass with two comparison variables is faster and lighter than any alternative.

Where This Problem Appears in Placement Tests

Number reversal comes up in two forms: as a standalone “write the code” task, and as a building block inside harder problems.

The palindrome check is the most common compound use. Reverse the number, compare it to the original, and the match determines whether it is a palindrome. Understanding the reversal loop makes the palindrome extension a two-line addition rather than a new problem.

Other problems that use the same digit-extraction pattern:

  • Sum of digits: use num % 10 to extract each digit and add it to a running total
  • Count digits: count the num / 10 iterations until num reaches 0
  • Check Armstrong number: extract each digit, cube it, and sum
  • Rearrange digits to form the largest number: extract, sort, reconstruct

Service-tier companies including TCS, Infosys, and Wipro include problems at this difficulty level in their coding screeners. Answering with only the code leaves the question incomplete. State the time complexity (O(log n)) and space complexity (O(1) iterative, O(log n) recursive) without waiting to be asked.

FACE Prep’s data structures interview questions guide covers 20 of the most frequently tested loop and array patterns with full complexity analysis for each.

Two approaches exist for this problem, but only the iterative one runs in O(1) space. That trade-off is what interviewers expect you to state unprompted, and the same space-efficiency reasoning carries into AI engineering work. TinkerLLM at ₹299 is FACE Prep’s entry point for students ready to carry that foundation into hands-on LLM API programming.

Primary sources

Frequently asked questions

Does this algorithm work for negative numbers?

The standard iterative and recursive implementations process only positive integers because the while loop runs while num > 0. To handle negatives, extract the sign first, reverse the absolute value, then re-apply the sign before returning.

What happens when the reversed number overflows int?

If the reversed result exceeds INT_MAX (2,147,483,647 in a 32-bit signed int), the value wraps, which is undefined behaviour in C and C++. Use long or long long for inputs that could produce large reversed values, and validate before printing.

What is the time complexity of reversing a number?

O(log n), where n is the input value. The number of digits in n is approximately log base 10 of n, and the loop runs exactly once per digit.

Can I reverse a number by converting it to a string first?

Yes. Convert the integer to a string, reverse it, and convert back. This is readable and works well in interviews, but uses O(d) extra space for the string where d is the digit count. The modulo method avoids that allocation.

What about trailing zeros, for example reversing 1200?

1200 reversed is 0021, which equals 21 as an integer. The algorithm drops leading zeros in the result naturally because integer zero at the front carries no value. If the problem requires preserving them, convert to string first.

Where does this problem appear in placement tests?

TCS iOCT Coding, AMCAT Automata, and Infosys InfyTQ include number-manipulation problems at this level. The expected answer is the iterative version with stated time and space complexity.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF