How to reverse the order of an int without turning it into a string

Joshua Wilson :

I have been tasked with the assignment of creating a method that will take the 3 digit int input by the user and output its reverse (123 - 321). I am not allowed to convert the int to a string or I will lose points, I also am not allowed to print anywhere other than main.

public class Lab01
{
  public int sumTheDigits(int num)
   {
      int sum = 0;
      while(num > 0)
      {
         sum = sum + num % 10;
         num = num/10;
      }
      return sum;
   }

   public int reverseTheOrder(int reverse)
   {
      return reverse;
   }

   public static void main(String[] args)
   {
      Scanner input = new Scanner(System.in); 

      Lab01 lab = new Lab01();
      System.out.println("Enter a three digit number: ");
      int theNum = input.nextInt();
      int theSum = lab.sumTheDigits(theNum);
      int theReverse = lab.reverseTheOrder(theSum);

      System.out.println("The sum of the digits of " + theNum + " is " + theSum);
  }
WJS :

You need to use the following.

  • % the remainder operator
  • / the division operator
  • * multiplication.
  • + addition
Say you have a number 987
n = 987
r = n % 10 = 7   remainder when dividing by 10
n = n/10 = 98    integer division
Now repeat with n until n = 0, keeping track of r.

Once you understand this you can experiment (perhaps on paper first) to see how to put them back in reverse order (using the last two operators). But remember that numbers ending in 0 like 980 will become 89 since leading 0's are dropped.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=334757&siteId=1