- Java program to reverse a number using while loop and using a function.
Given a number N, we have to reverse the sequence of digits of a N and print it on screen. After reversing the least significant digit will become the most significant digit and vice versa. In general the ith digit from left becomes the ith digit from right side of N.
For Example,Input Number : 6534211
Output Number : 1124356
- Get the least significant digit(right most digit) of N. rightDigit = N%10;
- Append it at the end of reverse number. reverse = (reverse * 10) + rightDigit;
- Remove right most digit from number. N = N/10;
- Repeat this process till N is greater than zero.
Java program to reverse a number using while loop
In this program we first take a number as input from user and store it in variable N and then reverse N by implementing above mentioned algorithm using a while loop. Here, we are using while loop but same can be implemented using a for or do-while loop also. Finally we print the reversed number on screen.
package com.tcc.java.programs; import java.util.Scanner; /** * Java Program to reverse a number */ public class ReverseNumber { public static void main(String[] args) { int N, reverse = 0, rightDigit; Scanner scanner; scanner = new Scanner(System.in); System.out.println("Enter an Integer"); N = scanner.nextInt(); while (N != 0) { rightDigit = N % 10; reverse = (reverse * 10) + rightDigit; N = N / 10; } System.out.format("Reversed Number = %d\n", reverse); } }Output
Enter an Integer 98765 Reversed Number = 56789
Java program to reverse the digits of a number using function
This java program is similar to above program except here we are using a user defined function "getReverseNumber" which takes an integer N as input parameter and returns it's reversed number.
package com.tcc.java.programs; import java.util.Scanner; /** * Java Program to reverse a number using function */ public class ReverseNumberFunction { public static void main(String[] args) { int N; Scanner scanner; scanner = new Scanner(System.in); System.out.println("Enter an Integer"); N = scanner.nextInt(); // Calling getReverseNumber method to reverse digits of N System.out.format("Reversed Number = %d\n", getReverseNumber(N)); } /** * Reverses the digits of a number */ public static int getReverseNumber(int N) { int reverse = 0, rightDigit; while (N != 0) { rightDigit = N % 10; reverse = (reverse * 10) + rightDigit; N = N / 10; } return reverse; } }Output
Enter an Integer 12034 Reversed Number = 43021
Enter an Integer 4 Reversed Number = 4