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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM