Monday, September 12, 2016

JAVA HOW TO PROGRAM, NINTH EDITION, DEITEL: CHAPTER SIX SOLUTIONS

Question: Reversing Digits

Write a method that takes an integer value and returns the number with its digits reversed. For example, given the number 7631, the method should return 1367. Incorporate the method into an application that reads a value from the user and displays the result.


Solution: Reversing Digits

import java.util.Scanner;

public class ReverseNumber {

   public static void main(String[] args) {
       Scanner input = new Scanner(System.in);
       System.out.print("Enter the number to be reversed : ");
       int entry = input.nextInt();
       int result = reverse(entry);
       System.out.println("The reversed number is " + result);
   }

   public static int reverse(int n) {
       int result = 0;
       int rem;
       while (n > 0) {
           rem = n % 10;
           n = n / 10;
           result = result * 10 + rem;
       }
       return result;
   }
}

No comments:

Post a Comment