Reverse of Number using Java - CodeMub

Introduction

In the world of programming, one frequently encounters tasks that involve manipulating and transforming data. One such task is reversing a number, a fundamental operation in computer science and mathematics. In this blog, we'll delve into the process of reversing a number using Java.

Concepts Used in Java

Input Handling with Scanner

Java provides the `Scanner` class for user input. It allows the program to read data from the standard input stream (in this case, the keyboard). In our code, we use `Scanner` to get a long integer as input.

Scanner inp = new Scanner(System.in);

long n = inp.nextLong();

Variables and Arithmetic Operations

Java, like many programming languages, utilizes variables to store and manipulate data. In our code, we use `long` variables to store the original number (`original`), the reversed number (`rev`), and a temporary variable for the remainder (`rem`).

long original = n;

long rev = 0, rem;

While Loop for Iteration

The `while` loop is employed to iterate through the digits of the number, extracting each digit and building the reversed number.

while (n != 0) {

    rem = n % 10;

    rev = (rev * 10) + rem;

    n = n / 10;

}

Logical Flow for Calculating Reverse

To reverse a number, the individual digits are extracted from the original number one by one using the modulo (`%`) operation. These digits are then added to the reversed number (`rev`) after being multiplied by 10 and adding the previous result. This process continues until all digits are processed, effectively reversing the order of digits.

Coding

Here's a breakdown of the code for reversing a number in Java:

import java.util.Scanner;

public class Reverse {

      public static void main(String args[]) {

        // Input

        try (Scanner inp = new Scanner(System.in)) {

            System.out.println("Enter the number:");

            long n = inp.nextLong();

            long original = n;

            long rev = 0, rem;

            // Reversing the number

            while (n != 0) {

                rem = n % 10;

                rev = (rev * 10) + rem;

                n = n / 10;

            }

            // Output

            System.out.println("Reverse of " + original + " is " + rev);

        }

    }

}


Output

When you run the program and input a number, it will output the reversed version of that number. For example:

Enter the number:

12345

Reverse of 12345 is 54321

Conclusion

Reversing a number is a basic yet essential programming task. This blog explored the Java concepts and logical flow behind reversing a number, providing a clear understanding of the code. The usage of `Scanner` for input, variables for storage, and a `while` loop for iteration were highlighted in the context of this practical example. The ability to reverse a number is a small but crucial skill in a programmer's toolkit.

Next Post Previous Post
No Comment
Add Comment
comment url