Java program to reverse a number :
In this tutorial ,we will learn how to reverse a number in Java. First we will take the number as input from the user, then convert it to a string and reverse it . Then again we will convert it back to integer.
Following steps are using in the program :
- Get the inger from the user using ‘Scanner’
- Convert it to a string using ‘String.valueOf()’
- Create an empty result string.
- Scan the string converted number character by character using a ‘for’ loop from last to first
- Append each character to the result string.
- After the loop is completed, convert the result string to integer using ‘Integer.valueOf()’
- Print out the result
Java example Program :
import java.util.Scanner; public class Main { /** * Utility functions */ static void println(String string) { System.out.println(string); } static void print(String string) { System.out.print(string); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); println("Enter a number you want to rotate : "); int number = sc.nextInt(); String strNumber = String.valueOf(number); String reverseNumberString = ""; for (int i = strNumber.length() - 1; i >= 0; i--) { reverseNumberString += strNumber.charAt(i); } int reverseNumber = Integer.valueOf(reverseNumberString); println("Reverse of the number is " + reverseNumber); } }
Sample Output :
Enter a number you want to rotate : 125467 Reverse of the number is 764521 Enter a number you want to rotate : 562948 Reverse of the number is 849265 Enter a number you want to rotate : 1 Reverse of the number is 1 Enter a number you want to rotate : 54 Reverse of the number is 45
Similar tutorials :
- Java program to check if a number is perfect or not
- Java program to get the maximum number holder Student
- Java program to find the sum of all digits of a number
- Java program to extract all numbers from a string
- Java program to check if a number is Pronic or Heteromecic
- Java program to find three numbers in an array with total sum zero