🔢 Reverse a Number in Java (Without Using Built-in Reverse Methods)
🧩 What problem are we solving?
The goal is to reverse the digits of an integer — for example, converting 122 into 221.
This is a classic example to understand how to work with loops, integer division, and the modulo operator in Java.
⚙️ Algorithm (Step by Step)
We want to rebuild the number by extracting its last digit and adding it to a new reversed number in each step.
Formula:
Step-by-Step Example
Let’s take the input number 122:
| Step | Number | Reverse Calculation | Reverse Result | New Number |
|---|---|---|---|---|
| 1 | 122 | (0 × 10) + (122 % 10) | 2 | 12 |
| 2 | 12 | (2 × 10) + (12 % 10) | 22 | 1 |
| 3 | 1 | (22 × 10) + (1 % 10) | 221 | 0 |
✅ Final Output: 221
🧠Key Concept
-
%(modulo) gives the last digit of a number.
→122 % 10 = 2 -
/(integer division) removes the last digit.
→122 / 10 = 12 -
Multiplying the current reverse by
10shifts digits left to make room for the next digit.
📘 Java Implementation
package com.vinod.test;
/**
* ReverseNumberExample
*
* Problem:
* Reverse the digits of an integer without using built-in reverse functions.
*
* Algorithm:
* 1. Initialize reverse = 0.
* 2. Repeat while number != 0:
* - Extract the last digit using number % 10.
* - Multiply reverse by 10 and add the extracted digit.
* - Divide number by 10 to remove the last digit.
* 3. Print the reversed number.
*
* Example:
* Input: 122
* Output: 221
*
* Time Complexity:
* O(log10(n)) → proportional to the number of digits.
*
* Space Complexity:
* O(1)
*
* Author: Vinod Kariyathungal Kumaran
*/
public class ReverseNumberExample {
public static void main(String[] args) {
int reverse = 0;
int number = 122;
System.out.println("Input number = " + number);
System.out.println("Intermediate steps:");
while (number != 0) {
reverse = (reverse * 10) + (number % 10);
System.out.println("Reverse = " + reverse);
number = number / 10;
System.out.println("Number = " + number);
}
System.out.println("Reversed number = " + reverse);
// Alternative method using StringBuilder
StringBuilder sb = new StringBuilder(String.valueOf(122));
System.out.println("Reversed number using StringBuilder = " + sb.reverse().toString());
}
}
No comments:
Post a Comment