Java逆序输出整数

题目要求:编写方法reverseDigit,将一个整数作为参数,并反向返回该数字。例如reverseDigit(123)的值是321。同时编写程序测试此方法。

说明:10的倍数的逆序,均以实际结果为准,如100的逆序为1。此方法也可以实现负数的逆序输出。

 1 import java.util.Scanner;
 2 
 3 public class Test {
 4     static int reverseDigit(int n) {
 5         int result = n, count = 1;        //先将n赋值给result,用count计数以便后续数组操作
 6         while ((result /= 10) != 0) {    //使用while循环,对result进行除10取整操作
 7             count++;                    //如果取整后不为0,则count加一
 8         }
 9         int[] list = new int[count];    //使用数组存放n的每一位,长度为count,注意此处result已经等于0
10         for (int i = 0; i < count; i++) {    //循环count次
11             list[i] = n % 10;            //存放n的每一位,从后往前,逆序存放
12             result += list[i] * Math.pow(10, count - 1 - i); //使用幂运算,底数为10,指数为count-1-i
13             n = n / 10;                    //n除10取整
14         }
15         return result;
16     }
17 
18     public static void main(String[] args) {
19         int n;
20         System.out.println("Please input a int:");
21         Scanner sc = new Scanner(System.in);
22         n = sc.nextInt();
23         System.out.printf("The reverse is %d !\n", reverseDigit(n));
24         sc.close();
25     }
26 }

猜你喜欢

转载自www.cnblogs.com/linkchen/p/10682572.html