學以致用——Java原始碼——16位以內任意整數的逆序數的輸出(Reversing Digits)
阿新 • • 發佈:2018-12-30
這道題其實並不簡單,涉及:
1. 整數位數的計算
2. 整數各個位數的值的計算
3. 整數的構成
遺留問題:Java long資料型別最大支援Long.MAX_VALUE = 9223372036854775807(共19位),但經過測試,本程式僅支援16位以內的計算,超過後會發生溢位而導致逆序結果不正確。留待以後細究。
package exercises.ch6Methods; import static java.lang.Math.pow; import java.util.*; //JHTP Exercise 6.26 (Reversing Digits) //by [email protected]
/** * *6.26(Reversing Digits) Write a method that takes an integer value and returns the *number with its digits reversed. For example, given the number 7631, the method should *return 1367. Incorporate the method into an application that reads a value from the user *and displays the result. * */ public class ReverseDigits { public static void main(String args[]) { long input; Scanner scan=new Scanner(System.in); do { System.out.printf("請輸入一個整數(輸入-1退出,最大支援16位任意整數):"); input = scan.nextLong(); long digits = input; long counter = 0; long reversed = 0; //計算該整數的位數(不斷除以10,直到小於10為止,運算次數即為該整數的位數,如123,除以10的結果依次為12,1,0,共計算了3次) while (digits > 0){ digits = digits/10; counter = counter + 1; } System.out.printf("該整數共有%d位%n",counter); //計算該整數的逆序數(通過求餘數運算計算) System.out.println("該整數逆序數的計算過程:"); while (input >0){ reversed =(long)( reversed + input%10*pow(10,counter-1)); System.out.println(reversed); input = input/10; counter--; } System.out.print("該整數的逆序數為:"); System.out.println(reversed); System.out.println(); } while (input != -1); System.out.println("已退出程式。"); scan.close(); } }
執行結果:
請輸入一個整數(輸入-1退出,最大支援16位任意整數):1234567891234567 該整數共有16位 該整數逆序數的計算過程: 7000000000000000 7600000000000000 7650000000000000 7654000000000000 7654300000000000 7654320000000000 7654321000000000 7654321900000000 7654321980000000 7654321987000000 7654321987600000 7654321987650000 7654321987654000 7654321987654300 7654321987654320 7654321987654321 該整數的逆序數為:7654321987654321 |
參考文章:
本程式的核心演算法參考了以下連結:
https://stackoverflow.com/questions/15349723/reversing-an-integer-in-java-using-a-for-loop