Skip to content

Java 逆序输出整数

博客园链接

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

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.Scanner;

public class Test {
    static int reverseDigit(int n) {
        int result = n, count = 1;        //先将n赋值给result,用count计数以便后续数组操作
        while ((result /= 10) != 0) {    //使用while循环,对result进行除10取整操作
            count++;                    //如果取整后不为0,则count加一
        }
        int[] list = new int[count];    //使用数组存放n的每一位,长度为count,注意此处result已经等于0
        for (int i = 0; i < count; i++) {    //循环count次
            list[i] = n % 10;            //存放n的每一位,从后往前,逆序存放
            result += list[i] * Math.pow(10, count - 1 - i); //使用幂运算,底数为10,指数为count-1-i
            n = n / 10;                    //n除10取整
        }
        return result;
    }

    public static void main(String[] args) {
        int n;
        System.out.println("Please input a int:");
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        System.out.printf("The reverse is %d !\n", reverseDigit(n));
        sc.close();
    }
}

Comments