如何反转int的顺序而不将其变成字符串

问题描述 投票:0回答:1

我的任务是创建一个方法,该方法将接受用户输入的3位数int并输出其倒数(123-321)。我不允许将int转换为字符串,否则会丢失点,也不允许在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);
java reverse dereference
1个回答
0
投票

您可以使用以下方法来计算数字的倒数。

public int reverseTheOrder(int reverse){
        int result = 0;
        while(reverse != 0){
            int rem = reverse%10;
            result = (result *10) + rem;
            reverse /= 10;
        }
      return result;
   }
© www.soinside.com 2019 - 2024. All rights reserved.