Saturday, 8 July 2017

Java Code to reverse the order of digits in a number

Problem:

Design an algorithm that accepts a positive integer and reverses the order of its digits.

Solution:

package com.myprograms;

import java.util.Scanner;

public class ReverseTheNumber {

public static void main(String[] args) {
System.out.println("the reverse number is " + reverseTheNumber(getTheNumber()));
}

public static int getTheNumber(){
Scanner s = new Scanner(System.in);
System.out.println("enter the n value");
int n = s.nextInt();
s.close();
return n;
}

private static int reverseTheNumber(int n){
int reverseNumber = 0;
while(n > 0){
reverseNumber = (reverseNumber * 10) + n % 10;
n = n/10;
}
return reverseNumber;
}
}


Output:

enter the n value
27953
the reverse number is 35972


No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...