Java Program To Reverse Digits of a Number Using Loop

Here is a Java program to reverse the sequence of digits of a number. To reverse a number in Java, we will first take an integer as input form user and store it in a int variable. We will reverse the digits of input number using below mentioned algorithm. After reversing we will prints the reversed number on screen. In this program, we will learn how to split a number into digits one by one and then reverse the sequence of digits.

Algorithm to reverse digits of a number
  • Get the least significant digit(right most digit or last digit) of the number.
    lastDigit = number%10;
  • Append it at the end of reverse number.
    reverse = (reverse * 10) + lastDigit;
  • Remove right most digit from number.
    number = number/10;
  • Repeat this process till number is greater than zero.

Java program to reverse digits of a number

package com.tcc.java.programs;

import java.io.*;

public class ReverseNumberDigits {
    public static void main(String args[]) throws Exception {
        int num=0, reverse, lastDigit;
        System.out.println("Enter an Integer");
        //take user input
        BufferedReader br = new BufferedReader(
           new InputStreamReader(System.in));
        num = Integer.parseInt(br.readLine());
        reverse = 0;
        while(num != 0) {
           lastDigit = num%10;
           reverse = reverse*10 + lastDigit;
           num = num/10;
        }
        
        System.out.println("Reversed Number : " + 
            reverse);
    }
}
Output
Enter an Integer
12345
Reversed Number : 54321

Recommended Posts
Java Program to Reverse a Number using Recursion
Java Program to Find LCM and GCD of Two Numbers
Java Program to Find Sum of Digits of a Number
Java Program to Count Number of Digits in a Number
Java Program to Check a Number is Prime Number or Not
Java Program to Print Multiplication Table of Number
Java Program to Find Factorial of a Number Using Recursion
Java Program to Find All Factors of a Number
Java Program to Calculate Compound Interest
Java Program to Make a Simple Calculator using Switch Statement
All Java Programs