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